chiark / gitweb /
journal: fix memory leak
[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, "unixexec:path=ssh,argv1=-xT,argv2=%s@%s,argv3=systemd-stdio-bridge", user, host);
181         else if (user)
182                 asprintf(&p, "unixexec:path=ssh,argv1=-xT,argv2=%s@localhost,argv3=systemd-stdio-bridge", user);
183         else if (host)
184                 asprintf(&p, "unixexec: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         bus = dbus_connection_open_private("unixexec:path=pkexec,argv1=" SYSTEMD_STDIO_BRIDGE_BINARY_PATH, error);
226         if (!bus)
227                 return -EIO;
228
229         dbus_connection_set_exit_on_disconnect(bus, FALSE);
230
231         if ((r = sync_auth(bus, error)) < 0) {
232                 dbus_connection_close(bus);
233                 dbus_connection_unref(bus);
234                 return r;
235         }
236
237         if (!dbus_bus_register(bus, error)) {
238                 dbus_connection_close(bus);
239                 dbus_connection_unref(bus);
240                 return r;
241         }
242
243         *_bus = bus;
244         return 0;
245 }
246
247 const char *bus_error_message(const DBusError *error) {
248         assert(error);
249
250         /* Sometimes the D-Bus server is a little bit too verbose with
251          * its error messages, so let's override them here */
252         if (dbus_error_has_name(error, DBUS_ERROR_ACCESS_DENIED))
253                 return "Access denied";
254
255         return error->message;
256 }
257
258 DBusHandlerResult bus_default_message_handler(
259                 DBusConnection *c,
260                 DBusMessage *message,
261                 const char *introspection,
262                 const char *interfaces,
263                 const BusBoundProperties *bound_properties) {
264
265         DBusError error;
266         DBusMessage *reply = NULL;
267         int r;
268
269         assert(c);
270         assert(message);
271
272         dbus_error_init(&error);
273
274         if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", "Introspect") && introspection) {
275
276                 if (!(reply = dbus_message_new_method_return(message)))
277                         goto oom;
278
279                 if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspection, DBUS_TYPE_INVALID))
280                         goto oom;
281
282         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "Get") && bound_properties) {
283                 const char *interface, *property;
284                 const BusBoundProperties *bp;
285                 const BusProperty *p;
286                 void *data;
287                 DBusMessageIter iter, sub;
288
289                 if (!dbus_message_get_args(
290                             message,
291                             &error,
292                             DBUS_TYPE_STRING, &interface,
293                             DBUS_TYPE_STRING, &property,
294                             DBUS_TYPE_INVALID))
295                         return bus_send_error_reply(c, message, &error, -EINVAL);
296
297                 for (bp = bound_properties; bp->interface; bp++) {
298                         if (!streq(bp->interface, interface))
299                                 continue;
300
301                         for (p = bp->properties; p->property; p++)
302                                 if (streq(p->property, property))
303                                         goto get_prop;
304                 }
305
306                 /* no match */
307                 if (!nulstr_contains(interfaces, interface))
308                         dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_INTERFACE, "Unknown interface");
309                 else
310                         dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_PROPERTY, "Unknown property");
311
312                 return bus_send_error_reply(c, message, &error, -EINVAL);
313
314 get_prop:
315                 reply = dbus_message_new_method_return(message);
316                 if (!reply)
317                         goto oom;
318
319                 dbus_message_iter_init_append(reply, &iter);
320
321                 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT, p->signature, &sub))
322                         goto oom;
323
324                 data = (char*)bp->base + p->offset;
325                 if (p->indirect)
326                         data = *(void**)data;
327                 r = p->append(&sub, property, data);
328                 if (r < 0) {
329                         if (r == -ENOMEM)
330                                 goto oom;
331
332                         dbus_message_unref(reply);
333                         return bus_send_error_reply(c, message, NULL, r);
334                 }
335
336                 if (!dbus_message_iter_close_container(&iter, &sub))
337                         goto oom;
338
339         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "GetAll") && bound_properties) {
340                 const char *interface;
341                 const BusBoundProperties *bp;
342                 const BusProperty *p;
343                 DBusMessageIter iter, sub, sub2, sub3;
344
345                 if (!dbus_message_get_args(
346                             message,
347                             &error,
348                             DBUS_TYPE_STRING, &interface,
349                             DBUS_TYPE_INVALID))
350                         return bus_send_error_reply(c, message, &error, -EINVAL);
351
352                 if (interface[0] && !nulstr_contains(interfaces, interface)) {
353                         dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_INTERFACE, "Unknown interface");
354                         return bus_send_error_reply(c, message, &error, -EINVAL);
355                 }
356
357                 if (!(reply = dbus_message_new_method_return(message)))
358                         goto oom;
359
360                 dbus_message_iter_init_append(reply, &iter);
361
362                 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub))
363                         goto oom;
364
365                 for (bp = bound_properties; bp->interface; bp++) {
366                         if (interface[0] && !streq(bp->interface, interface))
367                                 continue;
368
369                         for (p = bp->properties; p->property; p++) {
370                                 void *data;
371
372                                 if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, NULL, &sub2) ||
373                                     !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &p->property) ||
374                                     !dbus_message_iter_open_container(&sub2, DBUS_TYPE_VARIANT, p->signature, &sub3))
375                                         goto oom;
376
377                                 data = (char*)bp->base + p->offset;
378                                 if (p->indirect)
379                                         data = *(void**)data;
380                                 r = p->append(&sub3, p->property, data);
381                                 if (r < 0) {
382                                         if (r == -ENOMEM)
383                                                 goto oom;
384
385                                         dbus_message_unref(reply);
386                                         return bus_send_error_reply(c, message, NULL, r);
387                                 }
388
389                                 if (!dbus_message_iter_close_container(&sub2, &sub3) ||
390                                     !dbus_message_iter_close_container(&sub, &sub2))
391                                         goto oom;
392                         }
393                 }
394
395                 if (!dbus_message_iter_close_container(&iter, &sub))
396                         goto oom;
397
398         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "Set") && bound_properties) {
399                 const char *interface, *property;
400                 DBusMessageIter iter;
401                 const BusBoundProperties *bp;
402                 const BusProperty *p;
403                 DBusMessageIter sub;
404                 char *sig;
405
406                 if (!dbus_message_iter_init(message, &iter) ||
407                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
408                         return bus_send_error_reply(c, message, NULL, -EINVAL);
409
410                 dbus_message_iter_get_basic(&iter, &interface);
411
412                 if (!dbus_message_iter_next(&iter) ||
413                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
414                         return bus_send_error_reply(c, message, NULL, -EINVAL);
415
416                 dbus_message_iter_get_basic(&iter, &property);
417
418                 if (!dbus_message_iter_next(&iter) ||
419                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT ||
420                     dbus_message_iter_has_next(&iter))
421                         return bus_send_error_reply(c, message, NULL, -EINVAL);
422
423                 for (bp = bound_properties; bp->interface; bp++) {
424                         if (!streq(bp->interface, interface))
425                                 continue;
426
427                         for (p = bp->properties; p->property; p++)
428                                 if (streq(p->property, property))
429                                         goto set_prop;
430                 }
431
432                 /* no match */
433                 if (!nulstr_contains(interfaces, interface))
434                         dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_INTERFACE, "Unknown interface");
435                 else
436                         dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_PROPERTY, "Unknown property");
437
438                 return bus_send_error_reply(c, message, &error, -EINVAL);
439
440 set_prop:
441                 if (!p->set) {
442                         dbus_set_error_const(&error, DBUS_ERROR_PROPERTY_READ_ONLY, "Property read-only");
443                         return bus_send_error_reply(c, message, &error, -EINVAL);
444                 }
445
446                 dbus_message_iter_recurse(&iter, &sub);
447
448                 sig = dbus_message_iter_get_signature(&sub);
449                 if (!sig)
450                         goto oom;
451
452                 if (!streq(sig, p->signature)) {
453                         dbus_free(sig);
454                         return bus_send_error_reply(c, message, NULL, -EINVAL);
455                 }
456
457                 dbus_free(sig);
458
459                 r = p->set(&sub, property);
460                 if (r < 0) {
461                         if (r == -ENOMEM)
462                                 goto oom;
463                         return bus_send_error_reply(c, message, NULL, r);
464                 }
465
466                 reply = dbus_message_new_method_return(message);
467                 if (!reply)
468                         goto oom;
469         } else {
470                 const char *interface = dbus_message_get_interface(message);
471
472                 if (!interface || !nulstr_contains(interfaces, interface)) {
473                         dbus_set_error_const(&error, DBUS_ERROR_UNKNOWN_INTERFACE, "Unknown interface");
474                         return bus_send_error_reply(c, message, &error, -EINVAL);
475                 }
476         }
477
478         if (reply) {
479                 if (!dbus_connection_send(c, reply, NULL))
480                         goto oom;
481
482                 dbus_message_unref(reply);
483                 return DBUS_HANDLER_RESULT_HANDLED;
484         }
485
486         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
487
488 oom:
489         if (reply)
490                 dbus_message_unref(reply);
491
492         dbus_error_free(&error);
493
494         return DBUS_HANDLER_RESULT_NEED_MEMORY;
495 }
496
497 int bus_property_append_string(DBusMessageIter *i, const char *property, void *data) {
498         const char *t = data;
499
500         assert(i);
501         assert(property);
502
503         if (!t)
504                 t = "";
505
506         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t))
507                 return -ENOMEM;
508
509         return 0;
510 }
511
512 int bus_property_append_strv(DBusMessageIter *i, const char *property, void *data) {
513         char **t = data;
514
515         assert(i);
516         assert(property);
517
518         return bus_append_strv_iter(i, t);
519 }
520
521 int bus_property_append_bool(DBusMessageIter *i, const char *property, void *data) {
522         bool *b = data;
523         dbus_bool_t db;
524
525         assert(i);
526         assert(property);
527         assert(b);
528
529         db = *b;
530
531         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
532                 return -ENOMEM;
533
534         return 0;
535 }
536
537 int bus_property_append_tristate_false(DBusMessageIter *i, const char *property, void *data) {
538         int *b = data;
539         dbus_bool_t db;
540
541         assert(i);
542         assert(property);
543         assert(b);
544
545         db = *b > 0;
546
547         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
548                 return -ENOMEM;
549
550         return 0;
551 }
552
553 int bus_property_append_uint64(DBusMessageIter *i, const char *property, void *data) {
554         assert(i);
555         assert(property);
556         assert(data);
557
558         /* Let's ensure that usec_t is actually 64bit, and hence this
559          * function can be used for usec_t */
560         assert_cc(sizeof(uint64_t) == sizeof(usec_t));
561
562         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, data))
563                 return -ENOMEM;
564
565         return 0;
566 }
567
568 int bus_property_append_uint32(DBusMessageIter *i, const char *property, void *data) {
569         assert(i);
570         assert(property);
571         assert(data);
572
573         /* Let's ensure that pid_t, mode_t, uid_t, gid_t are actually
574          * 32bit, and hence this function can be used for
575          * pid_t/mode_t/uid_t/gid_t */
576         assert_cc(sizeof(uint32_t) == sizeof(pid_t));
577         assert_cc(sizeof(uint32_t) == sizeof(mode_t));
578         assert_cc(sizeof(uint32_t) == sizeof(unsigned));
579         assert_cc(sizeof(uint32_t) == sizeof(uid_t));
580         assert_cc(sizeof(uint32_t) == sizeof(gid_t));
581
582         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT32, data))
583                 return -ENOMEM;
584
585         return 0;
586 }
587
588 int bus_property_append_int32(DBusMessageIter *i, const char *property, void *data) {
589         assert(i);
590         assert(property);
591         assert(data);
592
593         assert_cc(sizeof(int32_t) == sizeof(int));
594
595         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, data))
596                 return -ENOMEM;
597
598         return 0;
599 }
600
601 int bus_property_append_size(DBusMessageIter *i, const char *property, void *data) {
602         uint64_t u;
603
604         assert(i);
605         assert(property);
606         assert(data);
607
608         u = (uint64_t) *(size_t*) data;
609
610         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &u))
611                 return -ENOMEM;
612
613         return 0;
614 }
615
616 int bus_property_append_ul(DBusMessageIter *i, const char *property, void *data) {
617         uint64_t u;
618
619         assert(i);
620         assert(property);
621         assert(data);
622
623         u = (uint64_t) *(unsigned long*) data;
624
625         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &u))
626                 return -ENOMEM;
627
628         return 0;
629 }
630
631 int bus_property_append_long(DBusMessageIter *i, const char *property, void *data) {
632         int64_t l;
633
634         assert(i);
635         assert(property);
636         assert(data);
637
638         l = (int64_t) *(long*) data;
639
640         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT64, &l))
641                 return -ENOMEM;
642
643         return 0;
644 }
645
646 const char *bus_errno_to_dbus(int error) {
647
648         switch(error) {
649
650         case -EINVAL:
651                 return DBUS_ERROR_INVALID_ARGS;
652
653         case -ENOMEM:
654                 return DBUS_ERROR_NO_MEMORY;
655
656         case -EPERM:
657         case -EACCES:
658                 return DBUS_ERROR_ACCESS_DENIED;
659
660         case -ESRCH:
661                 return DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN;
662
663         case -ENOENT:
664                 return DBUS_ERROR_FILE_NOT_FOUND;
665
666         case -EEXIST:
667                 return DBUS_ERROR_FILE_EXISTS;
668
669         case -ETIMEDOUT:
670         case -ETIME:
671                 return DBUS_ERROR_TIMEOUT;
672
673         case -EIO:
674                 return DBUS_ERROR_IO_ERROR;
675
676         case -ENETRESET:
677         case -ECONNABORTED:
678         case -ECONNRESET:
679                 return DBUS_ERROR_DISCONNECTED;
680         }
681
682         return DBUS_ERROR_FAILED;
683 }
684
685 DBusHandlerResult bus_send_error_reply(DBusConnection *c, DBusMessage *message, DBusError *berror, int error) {
686         DBusMessage *reply = NULL;
687         const char *name, *text;
688
689         if (berror && dbus_error_is_set(berror)) {
690                 name = berror->name;
691                 text = berror->message;
692         } else {
693                 name = bus_errno_to_dbus(error);
694                 text = strerror(-error);
695         }
696
697         if (!(reply = dbus_message_new_error(message, name, text)))
698                 goto oom;
699
700         if (!dbus_connection_send(c, reply, NULL))
701                 goto oom;
702
703         dbus_message_unref(reply);
704
705         if (berror)
706                 dbus_error_free(berror);
707
708         return DBUS_HANDLER_RESULT_HANDLED;
709
710 oom:
711         if (reply)
712                 dbus_message_unref(reply);
713
714         if (berror)
715                 dbus_error_free(berror);
716
717         return DBUS_HANDLER_RESULT_NEED_MEMORY;
718 }
719
720 DBusMessage* bus_properties_changed_new(const char *path, const char *interface, const char *properties) {
721         DBusMessage *m;
722         DBusMessageIter iter, sub;
723         const char *i;
724
725         assert(interface);
726         assert(properties);
727
728         if (!(m = dbus_message_new_signal(path, "org.freedesktop.DBus.Properties", "PropertiesChanged")))
729                 goto oom;
730
731         dbus_message_iter_init_append(m, &iter);
732
733         /* We won't send any property values, since they might be
734          * large and sometimes not cheap to generated */
735
736         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &interface) ||
737             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub) ||
738             !dbus_message_iter_close_container(&iter, &sub) ||
739             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub))
740                 goto oom;
741
742         NULSTR_FOREACH(i, properties)
743                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &i))
744                         goto oom;
745
746         if (!dbus_message_iter_close_container(&iter, &sub))
747                 goto oom;
748
749         return m;
750
751 oom:
752         if (m)
753                 dbus_message_unref(m);
754
755         return NULL;
756 }
757
758 uint32_t bus_flags_to_events(DBusWatch *bus_watch) {
759         unsigned flags;
760         uint32_t events = 0;
761
762         assert(bus_watch);
763
764         /* no watch flags for disabled watches */
765         if (!dbus_watch_get_enabled(bus_watch))
766                 return 0;
767
768         flags = dbus_watch_get_flags(bus_watch);
769
770         if (flags & DBUS_WATCH_READABLE)
771                 events |= EPOLLIN;
772         if (flags & DBUS_WATCH_WRITABLE)
773                 events |= EPOLLOUT;
774
775         return events | EPOLLHUP | EPOLLERR;
776 }
777
778 unsigned bus_events_to_flags(uint32_t events) {
779         unsigned flags = 0;
780
781         if (events & EPOLLIN)
782                 flags |= DBUS_WATCH_READABLE;
783         if (events & EPOLLOUT)
784                 flags |= DBUS_WATCH_WRITABLE;
785         if (events & EPOLLHUP)
786                 flags |= DBUS_WATCH_HANGUP;
787         if (events & EPOLLERR)
788                 flags |= DBUS_WATCH_ERROR;
789
790         return flags;
791 }
792
793 int bus_parse_strv(DBusMessage *m, char ***_l) {
794         DBusMessageIter iter;
795
796         assert(m);
797         assert(_l);
798
799         if (!dbus_message_iter_init(m, &iter))
800                 return -EINVAL;
801
802         return bus_parse_strv_iter(&iter, _l);
803 }
804
805 int bus_parse_strv_iter(DBusMessageIter *iter, char ***_l) {
806         DBusMessageIter sub;
807         unsigned n = 0, i = 0;
808         char **l;
809
810         assert(iter);
811         assert(_l);
812
813         if (dbus_message_iter_get_arg_type(iter) != DBUS_TYPE_ARRAY ||
814             dbus_message_iter_get_element_type(iter) != DBUS_TYPE_STRING)
815             return -EINVAL;
816
817         dbus_message_iter_recurse(iter, &sub);
818
819         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
820                 n++;
821                 dbus_message_iter_next(&sub);
822         }
823
824         if (!(l = new(char*, n+1)))
825                 return -ENOMEM;
826
827         dbus_message_iter_recurse(iter, &sub);
828
829         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
830                 const char *s;
831
832                 assert_se(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
833                 dbus_message_iter_get_basic(&sub, &s);
834
835                 if (!(l[i++] = strdup(s))) {
836                         strv_free(l);
837                         return -ENOMEM;
838                 }
839
840                 dbus_message_iter_next(&sub);
841         }
842
843         assert(i == n);
844         l[i] = NULL;
845
846         if (_l)
847                 *_l = l;
848
849         return 0;
850 }
851
852 int bus_append_strv_iter(DBusMessageIter *iter, char **l) {
853         DBusMessageIter sub;
854
855         assert(iter);
856
857         if (!dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, "s", &sub))
858                 return -ENOMEM;
859
860         STRV_FOREACH(l, l)
861                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, l))
862                         return -ENOMEM;
863
864         if (!dbus_message_iter_close_container(iter, &sub))
865                 return -ENOMEM;
866
867         return 0;
868 }
869
870 int bus_iter_get_basic_and_next(DBusMessageIter *iter, int type, void *data, bool next) {
871
872         assert(iter);
873         assert(data);
874
875         if (dbus_message_iter_get_arg_type(iter) != type)
876                 return -EIO;
877
878         dbus_message_iter_get_basic(iter, data);
879
880         if (!dbus_message_iter_next(iter) != !next)
881                 return -EIO;
882
883         return 0;
884 }
885
886 int generic_print_property(const char *name, DBusMessageIter *iter, bool all) {
887         assert(name);
888         assert(iter);
889
890         switch (dbus_message_iter_get_arg_type(iter)) {
891
892         case DBUS_TYPE_STRING: {
893                 const char *s;
894                 dbus_message_iter_get_basic(iter, &s);
895
896                 if (all || !isempty(s))
897                         printf("%s=%s\n", name, s);
898
899                 return 1;
900         }
901
902         case DBUS_TYPE_BOOLEAN: {
903                 dbus_bool_t b;
904
905                 dbus_message_iter_get_basic(iter, &b);
906                 printf("%s=%s\n", name, yes_no(b));
907
908                 return 1;
909         }
910
911         case DBUS_TYPE_UINT64: {
912                 uint64_t u;
913                 dbus_message_iter_get_basic(iter, &u);
914
915                 /* Yes, heuristics! But we can change this check
916                  * should it turn out to not be sufficient */
917
918                 if (endswith(name, "Timestamp")) {
919                         char timestamp[FORMAT_TIMESTAMP_MAX], *t;
920
921                         t = format_timestamp(timestamp, sizeof(timestamp), u);
922                         if (t || all)
923                                 printf("%s=%s\n", name, strempty(t));
924
925                 } else if (strstr(name, "USec")) {
926                         char timespan[FORMAT_TIMESPAN_MAX];
927
928                         printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u));
929                 } else
930                         printf("%s=%llu\n", name, (unsigned long long) u);
931
932                 return 1;
933         }
934
935         case DBUS_TYPE_UINT32: {
936                 uint32_t u;
937                 dbus_message_iter_get_basic(iter, &u);
938
939                 if (strstr(name, "UMask") || strstr(name, "Mode"))
940                         printf("%s=%04o\n", name, u);
941                 else
942                         printf("%s=%u\n", name, (unsigned) u);
943
944                 return 1;
945         }
946
947         case DBUS_TYPE_INT32: {
948                 int32_t i;
949                 dbus_message_iter_get_basic(iter, &i);
950
951                 printf("%s=%i\n", name, (int) i);
952                 return 1;
953         }
954
955         case DBUS_TYPE_DOUBLE: {
956                 double d;
957                 dbus_message_iter_get_basic(iter, &d);
958
959                 printf("%s=%g\n", name, d);
960                 return 1;
961         }
962
963         case DBUS_TYPE_ARRAY:
964
965                 if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_STRING) {
966                         DBusMessageIter sub;
967                         bool space = false;
968
969                         dbus_message_iter_recurse(iter, &sub);
970                         if (all ||
971                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
972                                 printf("%s=", name);
973
974                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
975                                         const char *s;
976
977                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
978                                         dbus_message_iter_get_basic(&sub, &s);
979                                         printf("%s%s", space ? " " : "", s);
980
981                                         space = true;
982                                         dbus_message_iter_next(&sub);
983                                 }
984
985                                 puts("");
986                         }
987
988                         return 1;
989
990                 } else if (dbus_message_iter_get_element_type(iter) == DBUS_TYPE_BYTE) {
991                         DBusMessageIter sub;
992
993                         dbus_message_iter_recurse(iter, &sub);
994                         if (all ||
995                             dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
996                                 printf("%s=", name);
997
998                                 while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
999                                         uint8_t u;
1000
1001                                         assert(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_BYTE);
1002                                         dbus_message_iter_get_basic(&sub, &u);
1003                                         printf("%02x", u);
1004
1005                                         dbus_message_iter_next(&sub);
1006                                 }
1007
1008                                 puts("");
1009                         }
1010
1011                         return 1;
1012                 }
1013
1014                 break;
1015         }
1016
1017         return 0;
1018 }
1019
1020 static void release_name_pending_cb(DBusPendingCall *pending, void *userdata) {
1021         DBusMessage *reply;
1022         DBusConnection *bus = userdata;
1023
1024         assert_se(reply = dbus_pending_call_steal_reply(pending));
1025         dbus_message_unref(reply);
1026
1027         dbus_connection_close(bus);
1028 }
1029
1030 void bus_async_unregister_and_exit(DBusConnection *bus, const char *name) {
1031         DBusMessage *m = NULL;
1032         DBusPendingCall *pending = NULL;
1033
1034         assert(bus);
1035
1036         /* We unregister the name here, but we continue to process
1037          * requests, until we get the response for it, so that all
1038          * requests are guaranteed to be processed. */
1039
1040         m = dbus_message_new_method_call(
1041                         DBUS_SERVICE_DBUS,
1042                         DBUS_PATH_DBUS,
1043                         DBUS_INTERFACE_DBUS,
1044                         "ReleaseName");
1045         if (!m)
1046                 goto oom;
1047
1048         if (!dbus_message_append_args(
1049                             m,
1050                             DBUS_TYPE_STRING,
1051                             &name,
1052                             DBUS_TYPE_INVALID))
1053                 goto oom;
1054
1055         if (!dbus_connection_send_with_reply(bus, m, &pending, -1))
1056                 goto oom;
1057
1058         if (!dbus_pending_call_set_notify(pending, release_name_pending_cb, bus, NULL))
1059                 goto oom;
1060
1061         dbus_message_unref(m);
1062         dbus_pending_call_unref(pending);
1063
1064         return;
1065
1066 oom:
1067         log_error("Out of memory");
1068
1069         if (pending) {
1070                 dbus_pending_call_cancel(pending);
1071                 dbus_pending_call_unref(pending);
1072         }
1073
1074         if (m)
1075                 dbus_message_unref(m);
1076 }
1077
1078 DBusHandlerResult bus_exit_idle_filter(DBusConnection *bus, DBusMessage *m, void *userdata) {
1079         usec_t *remain_until = userdata;
1080
1081         assert(bus);
1082         assert(m);
1083         assert(remain_until);
1084
1085         /* Everytime we get a new message we reset out timeout */
1086         *remain_until = now(CLOCK_MONOTONIC) + DEFAULT_EXIT_USEC;
1087
1088         if (dbus_message_is_signal(m, DBUS_INTERFACE_LOCAL, "Disconnected"))
1089                 dbus_connection_close(bus);
1090
1091         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1092 }