chiark / gitweb /
Fix broken Git repository URLs
[elogind.git] / src / dbus-common.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <assert.h>
23 #include <sys/socket.h>
24 #include <errno.h>
25 #include <unistd.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <dbus/dbus.h>
29 #include <string.h>
30 #include <sys/epoll.h>
31
32 #include "log.h"
33 #include "dbus-common.h"
34 #include "util.h"
35 #include "def.h"
36 #include "strv.h"
37
38 int bus_check_peercred(DBusConnection *c) {
39         int fd;
40         struct ucred ucred;
41         socklen_t l;
42
43         assert(c);
44
45         assert_se(dbus_connection_get_unix_fd(c, &fd));
46
47         l = sizeof(struct ucred);
48         if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0) {
49                 log_error("SO_PEERCRED failed: %m");
50                 return -errno;
51         }
52
53         if (l != sizeof(struct ucred)) {
54                 log_error("SO_PEERCRED returned wrong size.");
55                 return -E2BIG;
56         }
57
58         if (ucred.uid != 0 && ucred.uid != geteuid())
59                 return -EPERM;
60
61         return 1;
62 }
63
64 static int sync_auth(DBusConnection *bus, DBusError *error) {
65         usec_t begin, tstamp;
66
67         assert(bus);
68
69         /* This complexity should probably move into D-Bus itself:
70          *
71          * https://bugs.freedesktop.org/show_bug.cgi?id=35189 */
72
73         begin = tstamp = now(CLOCK_MONOTONIC);
74         for (;;) {
75
76                 if (tstamp > begin + DEFAULT_TIMEOUT_USEC)
77                         break;
78
79                 if (dbus_connection_get_is_authenticated(bus))
80                         break;
81
82                 if (!dbus_connection_read_write_dispatch(bus, ((begin + DEFAULT_TIMEOUT_USEC - tstamp) + USEC_PER_MSEC - 1) / USEC_PER_MSEC))
83                         break;
84
85                 tstamp = now(CLOCK_MONOTONIC);
86         }
87
88         if (!dbus_connection_get_is_connected(bus)) {
89                 dbus_set_error_const(error, DBUS_ERROR_NO_SERVER, "Connection terminated during authentication.");
90                 return -ECONNREFUSED;
91         }
92
93         if (!dbus_connection_get_is_authenticated(bus)) {
94                 dbus_set_error_const(error, DBUS_ERROR_TIMEOUT, "Failed to authenticate in time.");
95                 return -EACCES;
96         }
97
98         return 0;
99 }
100
101 int bus_connect(DBusBusType t, DBusConnection **_bus, bool *_private, DBusError *error) {
102         DBusConnection *bus = NULL;
103         int r;
104         bool private = true;
105
106         assert(_bus);
107
108         if (geteuid() == 0 && t == DBUS_BUS_SYSTEM) {
109                 /* If we are root, then let's talk directly to the
110                  * system instance, instead of going via the bus */
111
112                 bus = dbus_connection_open_private("unix:path=/run/systemd/private", error);
113                 if (!bus)
114                         return -EIO;
115
116         } else {
117                 if (t == DBUS_BUS_SESSION) {
118                         const char *e;
119
120                         /* If we are supposed to talk to the instance,
121                          * try via XDG_RUNTIME_DIR first, then
122                          * fallback to normal bus access */
123
124                         e = getenv("XDG_RUNTIME_DIR");
125                         if (e) {
126                                 char *p;
127
128                                 if (asprintf(&p, "unix:path=%s/systemd/private", e) < 0)
129                                         return -ENOMEM;
130
131                                 bus = dbus_connection_open_private(p, NULL);
132                                 free(p);
133                         }
134                 }
135
136                 if (!bus) {
137                         bus = dbus_bus_get_private(t, error);
138                         if (!bus)
139                                 return -EIO;
140
141                         private = false;
142                 }
143         }
144
145         dbus_connection_set_exit_on_disconnect(bus, FALSE);
146
147         if (private) {
148                 if (bus_check_peercred(bus) < 0) {
149                         dbus_connection_close(bus);
150                         dbus_connection_unref(bus);
151
152                         dbus_set_error_const(error, DBUS_ERROR_ACCESS_DENIED, "Failed to verify owner of bus.");
153                         return -EACCES;
154                 }
155         }
156
157         r = sync_auth(bus, error);
158         if (r < 0) {
159                 dbus_connection_close(bus);
160                 dbus_connection_unref(bus);
161                 return r;
162         }
163
164         if (_private)
165                 *_private = private;
166
167         *_bus = bus;
168         return 0;
169 }
170
171 int bus_connect_system_ssh(const char *user, const char *host, DBusConnection **_bus, DBusError *error) {
172         DBusConnection *bus;
173         char *p = NULL;
174         int r;
175
176         assert(_bus);
177         assert(user || host);
178
179         if (user && host)
180                 asprintf(&p, "exec:path=ssh,argv1=-xT,argv2=%s@%s,argv3=systemd-stdio-bridge", user, host);
181         else if (user)
182                 asprintf(&p, "exec:path=ssh,argv1=-xT,argv2=%s@localhost,argv3=systemd-stdio-bridge", user);
183         else if (host)
184                 asprintf(&p, "exec:path=ssh,argv1=-xT,argv2=%s,argv3=systemd-stdio-bridge", host);
185
186         if (!p) {
187                 dbus_set_error_const(error, DBUS_ERROR_NO_MEMORY, NULL);
188                 return -ENOMEM;
189         }
190
191         bus = dbus_connection_open_private(p, error);
192         free(p);
193
194         if (!bus)
195                 return -EIO;
196
197         dbus_connection_set_exit_on_disconnect(bus, FALSE);
198
199         if ((r = sync_auth(bus, error)) < 0) {
200                 dbus_connection_close(bus);
201                 dbus_connection_unref(bus);
202                 return r;
203         }
204
205         if (!dbus_bus_register(bus, error)) {
206                 dbus_connection_close(bus);
207                 dbus_connection_unref(bus);
208                 return r;
209         }
210
211         *_bus = bus;
212         return 0;
213 }
214
215 int bus_connect_system_polkit(DBusConnection **_bus, DBusError *error) {
216         DBusConnection *bus;
217         int r;
218
219         assert(_bus);
220
221         /* Don't bother with PolicyKit if we are root */
222         if (geteuid() == 0)
223                 return bus_connect(DBUS_BUS_SYSTEM, _bus, NULL, error);
224
225         if (!(bus = dbus_connection_open_private("exec:path=pkexec,argv1=" SYSTEMD_STDIO_BRIDGE_BINARY_PATH, error)))
226                 return -EIO;
227
228         dbus_connection_set_exit_on_disconnect(bus, FALSE);
229
230         if ((r = sync_auth(bus, error)) < 0) {
231                 dbus_connection_close(bus);
232                 dbus_connection_unref(bus);
233                 return r;
234         }
235
236         if (!dbus_bus_register(bus, error)) {
237                 dbus_connection_close(bus);
238                 dbus_connection_unref(bus);
239                 return r;
240         }
241
242         *_bus = bus;
243         return 0;
244 }
245
246 const char *bus_error_message(const DBusError *error) {
247         assert(error);
248
249         /* Sometimes the D-Bus server is a little bit too verbose with
250          * its error messages, so let's override them here */
251         if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED))
252                 return "Access denied";
253
254         return error->message;
255 }
256
257 DBusHandlerResult bus_default_message_handler(
258                 DBusConnection *c,
259                 DBusMessage *message,
260                 const char *introspection,
261                 const char *interfaces,
262                 const BusBoundProperties *bound_properties) {
263
264         DBusError error;
265         DBusMessage *reply = NULL;
266         int r;
267
268         assert(c);
269         assert(message);
270
271         dbus_error_init(&error);
272
273         if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", "Introspect") && introspection) {
274
275                 if (!(reply = dbus_message_new_method_return(message)))
276                         goto oom;
277
278                 if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspection, DBUS_TYPE_INVALID))
279                         goto oom;
280
281         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "Get") && bound_properties) {
282                 const char *interface, *property;
283                 const BusBoundProperties *bp;
284                 const BusProperty *p;
285                 void *data;
286                 DBusMessageIter iter, sub;
287
288                 if (!dbus_message_get_args(
289                             message,
290                             &error,
291                             DBUS_TYPE_STRING, &interface,
292                             DBUS_TYPE_STRING, &property,
293                             DBUS_TYPE_INVALID))
294                         return bus_send_error_reply(c, message, &error, -EINVAL);
295
296                 for (bp = bound_properties; bp->interface; bp++) {
297                         if (!streq(bp->interface, interface))
298                                 continue;
299
300                         for (p = bp->properties; p->property; p++)
301                                 if (streq(p->property, property))
302                                         goto get_prop;
303                 }
304
305                 /* no match */
306                 if (!nulstr_contains(interfaces, interface))
307                         dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_INTERFACE, "Unknown interface");
308                 else
309                         dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_PROPERTY, "Unknown property");
310
311                 return bus_send_error_reply(c, message, &error, -EINVAL);
312
313 get_prop:
314                 reply = dbus_message_new_method_return(message);
315                 if (!reply)
316                         goto oom;
317
318                 dbus_message_iter_init_append(reply, &iter);
319
320                 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT, p->signature, &sub))
321                         goto oom;
322
323                 data = (char*)bp->base + p->offset;
324                 if (p->indirect)
325                         data = *(void**)data;
326                 r = p->append(&sub, property, data);
327                 if (r < 0) {
328                         if (r == -ENOMEM)
329                                 goto oom;
330
331                         dbus_message_unref(reply);
332                         return bus_send_error_reply(c, message, NULL, r);
333                 }
334
335                 if (!dbus_message_iter_close_container(&iter, &sub))
336                         goto oom;
337
338         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "GetAll") && bound_properties) {
339                 const char *interface;
340                 const BusBoundProperties *bp;
341                 const BusProperty *p;
342                 DBusMessageIter iter, sub, sub2, sub3;
343
344                 if (!dbus_message_get_args(
345                             message,
346                             &error,
347                             DBUS_TYPE_STRING, &interface,
348                             DBUS_TYPE_INVALID))
349                         return bus_send_error_reply(c, message, &error, -EINVAL);
350
351                 if (interface[0] && !nulstr_contains(interfaces, interface)) {
352                         dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_INTERFACE, "Unknown interface");
353                         return bus_send_error_reply(c, message, &error, -EINVAL);
354                 }
355
356                 if (!(reply = dbus_message_new_method_return(message)))
357                         goto oom;
358
359                 dbus_message_iter_init_append(reply, &iter);
360
361                 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub))
362                         goto oom;
363
364                 for (bp = bound_properties; bp->interface; bp++) {
365                         if (interface[0] && !streq(bp->interface, interface))
366                                 continue;
367
368                         for (p = bp->properties; p->property; p++) {
369                                 void *data;
370
371                                 if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, NULL, &sub2) ||
372                                     !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &p->property) ||
373                                     !dbus_message_iter_open_container(&sub2, DBUS_TYPE_VARIANT, p->signature, &sub3))
374                                         goto oom;
375
376                                 data = (char*)bp->base + p->offset;
377                                 if (p->indirect)
378                                         data = *(void**)data;
379                                 r = p->append(&sub3, p->property, data);
380                                 if (r < 0) {
381                                         if (r == -ENOMEM)
382                                                 goto oom;
383
384                                         dbus_message_unref(reply);
385                                         return bus_send_error_reply(c, message, NULL, r);
386                                 }
387
388                                 if (!dbus_message_iter_close_container(&sub2, &sub3) ||
389                                     !dbus_message_iter_close_container(&sub, &sub2))
390                                         goto oom;
391                         }
392                 }
393
394                 if (!dbus_message_iter_close_container(&iter, &sub))
395                         goto oom;
396
397         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "Set") && bound_properties) {
398                 const char *interface, *property;
399                 DBusMessageIter iter;
400                 const BusBoundProperties *bp;
401                 const BusProperty *p;
402                 DBusMessageIter sub;
403                 char *sig;
404
405                 if (!dbus_message_iter_init(message, &iter) ||
406                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
407                         return bus_send_error_reply(c, message, NULL, -EINVAL);
408
409                 dbus_message_iter_get_basic(&iter, &interface);
410
411                 if (!dbus_message_iter_next(&iter) ||
412                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
413                         return bus_send_error_reply(c, message, NULL, -EINVAL);
414
415                 dbus_message_iter_get_basic(&iter, &property);
416
417                 if (!dbus_message_iter_next(&iter) ||
418                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT ||
419                     dbus_message_iter_has_next(&iter))
420                         return bus_send_error_reply(c, message, NULL, -EINVAL);
421
422                 for (bp = bound_properties; bp->interface; bp++) {
423                         if (!streq(bp->interface, interface))
424                                 continue;
425
426                         for (p = bp->properties; p->property; p++)
427                                 if (streq(p->property, property))
428                                         goto set_prop;
429                 }
430
431                 /* no match */
432                 if (!nulstr_contains(interfaces, interface))
433                         dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_INTERFACE, "Unknown interface");
434                 else
435                         dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_PROPERTY, "Unknown property");
436
437                 return bus_send_error_reply(c, message, &error, -EINVAL);
438
439 set_prop:
440                 if (!p->set) {
441                         dbus_set_error_const(&error, DBUS_ERROR_PROPERTY_READ_ONLY, "Property read-only");
442                         return bus_send_error_reply(c, message, &error, -EINVAL);
443                 }
444
445                 dbus_message_iter_recurse(&iter, &sub);
446
447                 sig = dbus_message_iter_get_signature(&sub);
448                 if (!sig)
449                         goto oom;
450
451                 if (!streq(sig, p->signature)) {
452                         dbus_free(sig);
453                         return bus_send_error_reply(c, message, NULL, -EINVAL);
454                 }
455
456                 dbus_free(sig);
457
458                 r = p->set(&sub, property);
459                 if (r < 0) {
460                         if (r == -ENOMEM)
461                                 goto oom;
462                         return bus_send_error_reply(c, message, NULL, r);
463                 }
464
465                 reply = dbus_message_new_method_return(message);
466                 if (!reply)
467                         goto oom;
468         } else {
469                 const char *interface = dbus_message_get_interface(message);
470
471                 if (!interface || !nulstr_contains(interfaces, interface)) {
472                         dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_INTERFACE, "Unknown interface");
473                         return bus_send_error_reply(c, message, &error, -EINVAL);
474                 }
475         }
476
477         if (reply) {
478                 if (!dbus_connection_send(c, reply, NULL))
479                         goto oom;
480
481                 dbus_message_unref(reply);
482                 return DBUS_HANDLER_RESULT_HANDLED;
483         }
484
485         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
486
487 oom:
488         if (reply)
489                 dbus_message_unref(reply);
490
491         dbus_error_free(&error);
492
493         return DBUS_HANDLER_RESULT_NEED_MEMORY;
494 }
495
496 int bus_property_append_string(DBusMessageIter *i, const char *property, void *data) {
497         const char *t = data;
498
499         assert(i);
500         assert(property);
501
502         if (!t)
503                 t = "";
504
505         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t))
506                 return -ENOMEM;
507
508         return 0;
509 }
510
511 int bus_property_append_strv(DBusMessageIter *i, const char *property, void *data) {
512         char **t = data;
513
514         assert(i);
515         assert(property);
516
517         return bus_append_strv_iter(i, t);
518 }
519
520 int bus_property_append_bool(DBusMessageIter *i, const char *property, void *data) {
521         bool *b = data;
522         dbus_bool_t db;
523
524         assert(i);
525         assert(property);
526         assert(b);
527
528         db = *b;
529
530         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
531                 return -ENOMEM;
532
533         return 0;
534 }
535
536 int bus_property_append_tristate_false(DBusMessageIter *i, const char *property, void *data) {
537         int *b = data;
538         dbus_bool_t db;
539
540         assert(i);
541         assert(property);
542         assert(b);
543
544         db = *b > 0;
545
546         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
547                 return -ENOMEM;
548
549         return 0;
550 }
551
552 int bus_property_append_uint64(DBusMessageIter *i, const char *property, void *data) {
553         assert(i);
554         assert(property);
555         assert(data);
556
557         /* Let's ensure that usec_t is actually 64bit, and hence this
558          * function can be used for usec_t */
559         assert_cc(sizeof(uint64_t) == sizeof(usec_t));
560
561         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, data))
562                 return -ENOMEM;
563
564         return 0;
565 }
566
567 int bus_property_append_uint32(DBusMessageIter *i, const char *property, void *data) {
568         assert(i);
569         assert(property);
570         assert(data);
571
572         /* Let's ensure that pid_t, mode_t, uid_t, gid_t are actually
573          * 32bit, and hence this function can be used for
574          * pid_t/mode_t/uid_t/gid_t */
575         assert_cc(sizeof(uint32_t) == sizeof(pid_t));
576         assert_cc(sizeof(uint32_t) == sizeof(mode_t));
577         assert_cc(sizeof(uint32_t) == sizeof(unsigned));
578         assert_cc(sizeof(uint32_t) == sizeof(uid_t));
579         assert_cc(sizeof(uint32_t) == sizeof(gid_t));
580
581         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT32, data))
582                 return -ENOMEM;
583
584         return 0;
585 }
586
587 int bus_property_append_int32(DBusMessageIter *i, const char *property, void *data) {
588         assert(i);
589         assert(property);
590         assert(data);
591
592         assert_cc(sizeof(int32_t) == sizeof(int));
593
594         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, data))
595                 return -ENOMEM;
596
597         return 0;
598 }
599
600 int bus_property_append_size(DBusMessageIter *i, const char *property, void *data) {
601         uint64_t u;
602
603         assert(i);
604         assert(property);
605         assert(data);
606
607         u = (uint64_t) *(size_t*) data;
608
609         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &u))
610                 return -ENOMEM;
611
612         return 0;
613 }
614
615 int bus_property_append_ul(DBusMessageIter *i, const char *property, void *data) {
616         uint64_t u;
617
618         assert(i);
619         assert(property);
620         assert(data);
621
622         u = (uint64_t) *(unsigned long*) data;
623
624         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &u))
625                 return -ENOMEM;
626
627         return 0;
628 }
629
630 int bus_property_append_long(DBusMessageIter *i, const char *property, void *data) {
631         int64_t l;
632
633         assert(i);
634         assert(property);
635         assert(data);
636
637         l = (int64_t) *(long*) data;
638
639         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT64, &l))
640                 return -ENOMEM;
641
642         return 0;
643 }
644
645 const char *bus_errno_to_dbus(int error) {
646
647         switch(error) {
648
649         case -EINVAL:
650                 return DBUS_ERROR_INVALID_ARGS;
651
652         case -ENOMEM:
653                 return DBUS_ERROR_NO_MEMORY;
654
655         case -EPERM:
656         case -EACCES:
657                 return DBUS_ERROR_ACCESS_DENIED;
658
659         case -ESRCH:
660                 return DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN;
661
662         case -ENOENT:
663                 return DBUS_ERROR_FILE_NOT_FOUND;
664
665         case -EEXIST:
666                 return DBUS_ERROR_FILE_EXISTS;
667
668         case -ETIMEDOUT:
669         case -ETIME:
670                 return DBUS_ERROR_TIMEOUT;
671
672         case -EIO:
673                 return DBUS_ERROR_IO_ERROR;
674
675         case -ENETRESET:
676         case -ECONNABORTED:
677         case -ECONNRESET:
678                 return DBUS_ERROR_DISCONNECTED;
679         }
680
681         return DBUS_ERROR_FAILED;
682 }
683
684 DBusHandlerResult bus_send_error_reply(DBusConnection *c, DBusMessage *message, DBusError *berror, int error) {
685         DBusMessage *reply = NULL;
686         const char *name, *text;
687
688         if (berror && dbus_error_is_set(berror)) {
689                 name = berror->name;
690                 text = berror->message;
691         } else {
692                 name = bus_errno_to_dbus(error);
693                 text = strerror(-error);
694         }
695
696         if (!(reply = dbus_message_new_error(message, name, text)))
697                 goto oom;
698
699         if (!dbus_connection_send(c, reply, NULL))
700                 goto oom;
701
702         dbus_message_unref(reply);
703
704         if (berror)
705                 dbus_error_free(berror);
706
707         return DBUS_HANDLER_RESULT_HANDLED;
708
709 oom:
710         if (reply)
711                 dbus_message_unref(reply);
712
713         if (berror)
714                 dbus_error_free(berror);
715
716         return DBUS_HANDLER_RESULT_NEED_MEMORY;
717 }
718
719 DBusMessage* bus_properties_changed_new(const char *path, const char *interface, const char *properties) {
720         DBusMessage *m;
721         DBusMessageIter iter, sub;
722         const char *i;
723
724         assert(interface);
725         assert(properties);
726
727         if (!(m = dbus_message_new_signal(path, "org.freedesktop.DBus.Properties", "PropertiesChanged")))
728                 goto oom;
729
730         dbus_message_iter_init_append(m, &iter);
731
732         /* We won't send any property values, since they might be
733          * large and sometimes not cheap to generated */
734
735         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &interface) ||
736             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub) ||
737             !dbus_message_iter_close_container(&iter, &sub) ||
738             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub))
739                 goto oom;
740
741         NULSTR_FOREACH(i, properties)
742                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &i))
743                         goto oom;
744
745         if (!dbus_message_iter_close_container(&iter, &sub))
746                 goto oom;
747
748         return m;
749
750 oom:
751         if (m)
752                 dbus_message_unref(m);
753
754         return NULL;
755 }
756
757 uint32_t bus_flags_to_events(DBusWatch *bus_watch) {
758         unsigned flags;
759         uint32_t events = 0;
760
761         assert(bus_watch);
762
763         /* no watch flags for disabled watches */
764         if (!dbus_watch_get_enabled(bus_watch))
765                 return 0;
766
767         flags = dbus_watch_get_flags(bus_watch);
768
769         if (flags & DBUS_WATCH_READABLE)
770                 events |= EPOLLIN;
771         if (flags & DBUS_WATCH_WRITABLE)
772                 events |= EPOLLOUT;
773
774         return events | EPOLLHUP | EPOLLERR;
775 }
776
777 unsigned bus_events_to_flags(uint32_t events) {
778         unsigned flags = 0;
779
780         if (events & EPOLLIN)
781                 flags |= DBUS_WATCH_READABLE;
782         if (events & EPOLLOUT)
783                 flags |= DBUS_WATCH_WRITABLE;
784         if (events & EPOLLHUP)
785                 flags |= DBUS_WATCH_HANGUP;
786         if (events & EPOLLERR)
787                 flags |= DBUS_WATCH_ERROR;
788
789         return flags;
790 }
791
792 int bus_parse_strv(DBusMessage *m, char ***_l) {
793         DBusMessageIter iter;
794
795         assert(m);
796         assert(_l);
797
798         if (!dbus_message_iter_init(m, &iter))
799                 return -EINVAL;
800
801         return bus_parse_strv_iter(&iter, _l);
802 }
803
804 int bus_parse_strv_iter(DBusMessageIter *iter, char ***_l) {
805         DBusMessageIter sub;
806         unsigned n = 0, i = 0;
807         char **l;
808
809         assert(iter);
810         assert(_l);
811
812         if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY ||
813             dbus_message_iter_get_element_type(iter) != DBUS_TYPE_STRING)
814             return -EINVAL;
815
816         dbus_message_iter_recurse(iter, &sub);
817
818         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
819                 n++;
820                 dbus_message_iter_next(&sub);
821         }
822
823         if (!(l = new(char*, n+1)))
824                 return -ENOMEM;
825
826         dbus_message_iter_recurse(iter, &sub);
827
828         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
829                 const char *s;
830
831                 assert_se(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
832                 dbus_message_iter_get_basic(&sub, &s);
833
834                 if (!(l[i++] = strdup(s))) {
835                         strv_free(l);
836                         return -ENOMEM;
837                 }
838
839                 dbus_message_iter_next(&sub);
840         }
841
842         assert(i == n);
843         l[i] = NULL;
844
845         if (_l)
846                 *_l = l;
847
848         return 0;
849 }
850
851 int bus_append_strv_iter(DBusMessageIter *iter, char **l) {
852         DBusMessageIter sub;
853
854         assert(iter);
855
856         if (!dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, "s", &sub))
857                 return -ENOMEM;
858
859         STRV_FOREACH(l, l)
860                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, l))
861                         return -ENOMEM;
862
863         if (!dbus_message_iter_close_container(iter, &sub))
864                 return -ENOMEM;
865
866         return 0;
867 }
868
869 int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
870
871         assert(iter);
872         assert(data);
873
874         if (dbus_message_iter_get_arg_type(iter) != type)
875                 return -EIO;
876
877         dbus_message_iter_get_basic(iter, data);
878
879         if (!dbus_message_iter_next(iter) != !next)
880                 return -EIO;
881
882         return 0;
883 }
884
885 int generic_print_property(const char *name, DBusMessageIter *iter, bool all) {
886         assert(name);
887         assert(iter);
888
889         switch (dbus_message_iter_get_arg_type(iter)) {
890
891         case DBUS_TYPE_STRING: {
892                 const char *s;
893                 dbus_message_iter_get_basic(iter, &s);
894
895                 if (all || !isempty(s))
896                         printf("%s=%s\n", name, s);
897
898                 return 1;
899         }
900
901         case DBUS_TYPE_BOOLEAN: {
902                 dbus_bool_t b;
903
904                 dbus_message_iter_get_basic(iter, &b);
905                 printf("%s=%s\n", name, yes_no(b));
906
907                 return 1;
908         }
909
910         case DBUS_TYPE_UINT64: {
911                 uint64_t u;
912                 dbus_message_iter_get_basic(iter, &u);
913
914                 /* Yes, heuristics! But we can change this check
915                  * should it turn out to not be sufficient */
916
917                 if (endswith(name, "Timestamp")) {
918                         char timestamp[FORMAT_TIMESTAMP_MAX], *t;
919
920                         t = format_timestamp(timestamp, sizeof(timestamp), u);
921                         if (t || all)
922                                 printf("%s=%s\n", name, strempty(t));
923
924                 } else if (strstr(name, "USec")) {
925                         char timespan[FORMAT_TIMESPAN_MAX];
926
927                         printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
928                 } else
929                         printf("%s=%llu\n", name, (unsigned long long) u);
930
931                 return 1;
932         }
933
934         case DBUS_TYPE_UINT32: {
935                 uint32_t u;
936                 dbus_message_iter_get_basic(iter, &u);
937
938                 if (strstr(name, "UMask") || strstr(name, "Mode"))
939                         printf("%s=%04o\n", name, u);
940                 else
941                         printf("%s=%u\n", name, (unsigned) u);
942
943                 return 1;
944         }
945
946         case DBUS_TYPE_INT32: {
947                 int32_t i;
948                 dbus_message_iter_get_basic(iter, &i);
949
950                 printf("%s=%i\n", name, (int) i);
951                 return 1;
952         }
953
954         case DBUS_TYPE_DOUBLE: {
955                 double d;
956                 dbus_message_iter_get_basic(iter, &d);
957
958                 printf("%s=%g\n", name, d);
959                 return 1;
960         }
961
962         case DBUS_TYPE_ARRAY:
963
964                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
965                         DBusMessageIter sub;
966                         bool space = false;
967
968                         dbus_message_iter_recurse(iter, &sub);
969                         if (all ||
970                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
971                                 printf("%s=", name);
972
973                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
974                                         const char *s;
975
976                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
977                                         dbus_message_iter_get_basic(&sub, &s);
978                                         printf("%s%s", space ? " " : "", s);
979
980                                         space = true;
981                                         dbus_message_iter_next(&sub);
982                                 }
983
984                                 puts("");
985                         }
986
987                         return 1;
988
989                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
990                         DBusMessageIter sub;
991
992                         dbus_message_iter_recurse(iter, &sub);
993                         if (all ||
994                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
995                                 printf("%s=", name);
996
997                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
998                                         uint8_t u;
999
1000                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
1001                                         dbus_message_iter_get_basic(&sub, &u);
1002                                         printf("%02x", u);
1003
1004                                         dbus_message_iter_next(&sub);
1005                                 }
1006
1007                                 puts("");
1008                         }
1009
1010                         return 1;
1011                 }
1012
1013                 break;
1014         }
1015
1016         return 0;
1017 }
1018
1019 static void release_name_pending_cb(DBusPendingCall *pending, void *userdata) {
1020         DBusMessage *reply;
1021         DBusConnection *bus = userdata;
1022
1023         assert_se(reply = dbus_pending_call_steal_reply(pending));
1024         dbus_message_unref(reply);
1025
1026         dbus_connection_close(bus);
1027 }
1028
1029 void bus_async_unregister_and_exit(DBusConnection *bus, const char *name) {
1030         DBusMessage *m = NULL;
1031         DBusPendingCall *pending = NULL;
1032
1033         assert(bus);
1034
1035         /* We unregister the name here, but we continue to process
1036          * requests, until we get the response for it, so that all
1037          * requests are guaranteed to be processed. */
1038
1039         m = dbus_message_new_method_call(
1040                         DBUS_SERVICE_DBUS,
1041                         DBUS_PATH_DBUS,
1042                         DBUS_INTERFACE_DBUS,
1043                         "ReleaseName");
1044         if (!m)
1045                 goto oom;
1046
1047         if (!dbus_message_append_args(
1048                             m,
1049                             DBUS_TYPE_STRING,
1050                             &name,
1051                             DBUS_TYPE_INVALID))
1052                 goto oom;
1053
1054         if (!dbus_connection_send_with_reply(bus, m, &pending, -1))
1055                 goto oom;
1056
1057         if (!dbus_pending_call_set_notify(pending, release_name_pending_cb, bus, NULL))
1058                 goto oom;
1059
1060         dbus_message_unref(m);
1061         dbus_pending_call_unref(pending);
1062
1063         return;
1064
1065 oom:
1066         log_error("Out of memory");
1067
1068         if (pending) {
1069                 dbus_pending_call_cancel(pending);
1070                 dbus_pending_call_unref(pending);
1071         }
1072
1073         if (m)
1074                 dbus_message_unref(m);
1075 }
1076
1077 DBusHandlerResult bus_exit_idle_filter(DBusConnection *bus, DBusMessage *m, void *userdata) {
1078         usec_t *remain_until = userdata;
1079
1080         assert(bus);
1081         assert(m);
1082         assert(remain_until);
1083
1084         /* Everytime we get a new message we reset out timeout */
1085         *remain_until = now(CLOCK_MONOTONIC) + DEFAULT_EXIT_USEC;
1086
1087         if (dbus_message_is_signal(m, DBUS_INTERFACE_LOCAL, "Disconnected"))
1088                 dbus_connection_close(bus);
1089
1090         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1091 }