chiark / gitweb /
0b77d3f85d411548b2fbe91ccd714721d000908b
[elogind.git] / src / shared / bus-util.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2013 Lennart Poettering
5
6   systemd is free software; you can redistribute it and/or modify it
7   under the terms of the GNU Lesser General Public License as published by
8   the Free Software Foundation; either version 2.1 of the License, or
9   (at your option) any later version.
10
11   systemd is distributed in the hope that it will be useful, but
12   WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14   Lesser General Public License for more details.
15
16   You should have received a copy of the GNU Lesser General Public License
17   along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <inttypes.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/ioctl.h>
27 #include <sys/resource.h>
28 #include <sys/socket.h>
29 #include <unistd.h>
30
31 #include "sd-bus-protocol.h"
32 #include "sd-bus.h"
33 #include "sd-daemon.h"
34 #include "sd-event.h"
35 #include "sd-id128.h"
36
37 #include "alloc-util.h"
38 #include "bus-internal.h"
39 #include "bus-label.h"
40 #include "bus-message.h"
41 #include "bus-util.h"
42 #include "def.h"
43 #include "escape.h"
44 #include "fd-util.h"
45 #include "missing.h"
46 #include "parse-util.h"
47 #include "proc-cmdline.h"
48 //#include "rlimit-util.h"
49 #include "stdio-util.h"
50 #include "strv.h"
51 #include "user-util.h"
52
53 #if 0 /// UNNEEDED by elogind
54 static int name_owner_change_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
55         sd_event *e = userdata;
56
57         assert(m);
58         assert(e);
59
60         sd_bus_close(sd_bus_message_get_bus(m));
61         sd_event_exit(e, 0);
62
63         return 1;
64 }
65
66 int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name) {
67         _cleanup_free_ char *match = NULL;
68         const char *unique;
69         int r;
70
71         assert(e);
72         assert(bus);
73         assert(name);
74
75         /* We unregister the name here and then wait for the
76          * NameOwnerChanged signal for this event to arrive before we
77          * quit. We do this in order to make sure that any queued
78          * requests are still processed before we really exit. */
79
80         r = sd_bus_get_unique_name(bus, &unique);
81         if (r < 0)
82                 return r;
83
84         r = asprintf(&match,
85                      "sender='org.freedesktop.DBus',"
86                      "type='signal',"
87                      "interface='org.freedesktop.DBus',"
88                      "member='NameOwnerChanged',"
89                      "path='/org/freedesktop/DBus',"
90                      "arg0='%s',"
91                      "arg1='%s',"
92                      "arg2=''", name, unique);
93         if (r < 0)
94                 return -ENOMEM;
95
96         r = sd_bus_add_match(bus, NULL, match, name_owner_change_callback, e);
97         if (r < 0)
98                 return r;
99
100         r = sd_bus_release_name(bus, name);
101         if (r < 0)
102                 return r;
103
104         return 0;
105 }
106
107 int bus_event_loop_with_idle(
108                 sd_event *e,
109                 sd_bus *bus,
110                 const char *name,
111                 usec_t timeout,
112                 check_idle_t check_idle,
113                 void *userdata) {
114         bool exiting = false;
115         int r, code;
116
117         assert(e);
118         assert(bus);
119         assert(name);
120
121         for (;;) {
122                 bool idle;
123
124                 r = sd_event_get_state(e);
125                 if (r < 0)
126                         return r;
127                 if (r == SD_EVENT_FINISHED)
128                         break;
129
130                 if (check_idle)
131                         idle = check_idle(userdata);
132                 else
133                         idle = true;
134
135                 r = sd_event_run(e, exiting || !idle ? (uint64_t) -1 : timeout);
136                 if (r < 0)
137                         return r;
138
139                 if (r == 0 && !exiting && idle) {
140
141                         r = sd_bus_try_close(bus);
142                         if (r == -EBUSY)
143                                 continue;
144
145                         /* Fallback for dbus1 connections: we
146                          * unregister the name and wait for the
147                          * response to come through for it */
148                         if (r == -EOPNOTSUPP) {
149
150                                 /* Inform the service manager that we
151                                  * are going down, so that it will
152                                  * queue all further start requests,
153                                  * instead of assuming we are already
154                                  * running. */
155                                 sd_notify(false, "STOPPING=1");
156
157                                 r = bus_async_unregister_and_exit(e, bus, name);
158                                 if (r < 0)
159                                         return r;
160
161                                 exiting = true;
162                                 continue;
163                         }
164
165                         if (r < 0)
166                                 return r;
167
168                         sd_event_exit(e, 0);
169                         break;
170                 }
171         }
172
173         r = sd_event_get_exit_code(e, &code);
174         if (r < 0)
175                 return r;
176
177         return code;
178 }
179 #endif // 0
180
181 int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error) {
182         _cleanup_(sd_bus_message_unrefp) sd_bus_message *rep = NULL;
183         int r, has_owner = 0;
184
185         assert(c);
186         assert(name);
187
188         r = sd_bus_call_method(c,
189                                "org.freedesktop.DBus",
190                                "/org/freedesktop/dbus",
191                                "org.freedesktop.DBus",
192                                "NameHasOwner",
193                                error,
194                                &rep,
195                                "s",
196                                name);
197         if (r < 0)
198                 return r;
199
200         r = sd_bus_message_read_basic(rep, 'b', &has_owner);
201         if (r < 0)
202                 return sd_bus_error_set_errno(error, r);
203
204         return has_owner;
205 }
206
207 static int check_good_user(sd_bus_message *m, uid_t good_user) {
208         _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
209         uid_t sender_uid;
210         int r;
211
212         assert(m);
213
214         if (good_user == UID_INVALID)
215                 return 0;
216
217         r = sd_bus_query_sender_creds(m, SD_BUS_CREDS_EUID, &creds);
218         if (r < 0)
219                 return r;
220
221         /* Don't trust augmented credentials for authorization */
222         assert_return((sd_bus_creds_get_augmented_mask(creds) & SD_BUS_CREDS_EUID) == 0, -EPERM);
223
224         r = sd_bus_creds_get_euid(creds, &sender_uid);
225         if (r < 0)
226                 return r;
227
228         return sender_uid == good_user;
229 }
230
231 int bus_test_polkit(
232                 sd_bus_message *call,
233                 int capability,
234                 const char *action,
235                 const char **details,
236                 uid_t good_user,
237                 bool *_challenge,
238                 sd_bus_error *e) {
239
240         int r;
241
242         assert(call);
243         assert(action);
244
245         /* Tests non-interactively! */
246
247         r = check_good_user(call, good_user);
248         if (r != 0)
249                 return r;
250
251         r = sd_bus_query_sender_privilege(call, capability);
252         if (r < 0)
253                 return r;
254         else if (r > 0)
255                 return 1;
256 #ifdef ENABLE_POLKIT
257         else {
258                 _cleanup_(sd_bus_message_unrefp) sd_bus_message *request = NULL;
259                 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
260                 int authorized = false, challenge = false;
261                 const char *sender, **k, **v;
262
263                 sender = sd_bus_message_get_sender(call);
264                 if (!sender)
265                         return -EBADMSG;
266
267                 r = sd_bus_message_new_method_call(
268                                 call->bus,
269                                 &request,
270                                 "org.freedesktop.PolicyKit1",
271                                 "/org/freedesktop/PolicyKit1/Authority",
272                                 "org.freedesktop.PolicyKit1.Authority",
273                                 "CheckAuthorization");
274                 if (r < 0)
275                         return r;
276
277                 r = sd_bus_message_append(
278                                 request,
279                                 "(sa{sv})s",
280                                 "system-bus-name", 1, "name", "s", sender,
281                                 action);
282                 if (r < 0)
283                         return r;
284
285                 r = sd_bus_message_open_container(request, 'a', "{ss}");
286                 if (r < 0)
287                         return r;
288
289                 STRV_FOREACH_PAIR(k, v, details) {
290                         r = sd_bus_message_append(request, "{ss}", *k, *v);
291                         if (r < 0)
292                                 return r;
293                 }
294
295                 r = sd_bus_message_close_container(request);
296                 if (r < 0)
297                         return r;
298
299                 r = sd_bus_message_append(request, "us", 0, NULL);
300                 if (r < 0)
301                         return r;
302
303                 r = sd_bus_call(call->bus, request, 0, e, &reply);
304                 if (r < 0) {
305                         /* Treat no PK available as access denied */
306                         if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN)) {
307                                 sd_bus_error_free(e);
308                                 return -EACCES;
309                         }
310
311                         return r;
312                 }
313
314                 r = sd_bus_message_enter_container(reply, 'r', "bba{ss}");
315                 if (r < 0)
316                         return r;
317
318                 r = sd_bus_message_read(reply, "bb", &authorized, &challenge);
319                 if (r < 0)
320                         return r;
321
322                 if (authorized)
323                         return 1;
324
325                 if (_challenge) {
326                         *_challenge = challenge;
327                         return 0;
328                 }
329         }
330 #endif
331
332         return -EACCES;
333 }
334
335 #ifdef ENABLE_POLKIT
336
337 typedef struct AsyncPolkitQuery {
338         sd_bus_message *request, *reply;
339         sd_bus_message_handler_t callback;
340         void *userdata;
341         sd_bus_slot *slot;
342         Hashmap *registry;
343 } AsyncPolkitQuery;
344
345 static void async_polkit_query_free(AsyncPolkitQuery *q) {
346
347         if (!q)
348                 return;
349
350         sd_bus_slot_unref(q->slot);
351
352         if (q->registry && q->request)
353                 hashmap_remove(q->registry, q->request);
354
355         sd_bus_message_unref(q->request);
356         sd_bus_message_unref(q->reply);
357
358         free(q);
359 }
360
361 static int async_polkit_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
362         _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
363         AsyncPolkitQuery *q = userdata;
364         int r;
365
366         assert(reply);
367         assert(q);
368
369         q->slot = sd_bus_slot_unref(q->slot);
370         q->reply = sd_bus_message_ref(reply);
371
372         r = sd_bus_message_rewind(q->request, true);
373         if (r < 0) {
374                 r = sd_bus_reply_method_errno(q->request, r, NULL);
375                 goto finish;
376         }
377
378         r = q->callback(q->request, q->userdata, &error_buffer);
379         r = bus_maybe_reply_error(q->request, r, &error_buffer);
380
381 finish:
382         async_polkit_query_free(q);
383
384         return r;
385 }
386
387 #endif
388
389 int bus_verify_polkit_async(
390                 sd_bus_message *call,
391                 int capability,
392                 const char *action,
393                 const char **details,
394                 bool interactive,
395                 uid_t good_user,
396                 Hashmap **registry,
397                 sd_bus_error *error) {
398
399 #ifdef ENABLE_POLKIT
400         _cleanup_(sd_bus_message_unrefp) sd_bus_message *pk = NULL;
401         AsyncPolkitQuery *q;
402         const char *sender, **k, **v;
403         sd_bus_message_handler_t callback;
404         void *userdata;
405         int c;
406 #endif
407         int r;
408
409         assert(call);
410         assert(action);
411         assert(registry);
412
413         r = check_good_user(call, good_user);
414         if (r != 0)
415                 return r;
416
417 #ifdef ENABLE_POLKIT
418         q = hashmap_get(*registry, call);
419         if (q) {
420                 int authorized, challenge;
421
422                 /* This is the second invocation of this function, and
423                  * there's already a response from polkit, let's
424                  * process it */
425                 assert(q->reply);
426
427                 if (sd_bus_message_is_method_error(q->reply, NULL)) {
428                         const sd_bus_error *e;
429
430                         /* Copy error from polkit reply */
431                         e = sd_bus_message_get_error(q->reply);
432                         sd_bus_error_copy(error, e);
433
434                         /* Treat no PK available as access denied */
435                         if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN))
436                                 return -EACCES;
437
438                         return -sd_bus_error_get_errno(e);
439                 }
440
441                 r = sd_bus_message_enter_container(q->reply, 'r', "bba{ss}");
442                 if (r >= 0)
443                         r = sd_bus_message_read(q->reply, "bb", &authorized, &challenge);
444
445                 if (r < 0)
446                         return r;
447
448                 if (authorized)
449                         return 1;
450
451                 if (challenge)
452                         return sd_bus_error_set(error, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED, "Interactive authentication required.");
453
454                 return -EACCES;
455         }
456 #endif
457
458         r = sd_bus_query_sender_privilege(call, capability);
459         if (r < 0)
460                 return r;
461         else if (r > 0)
462                 return 1;
463
464 #ifdef ENABLE_POLKIT
465         if (sd_bus_get_current_message(call->bus) != call)
466                 return -EINVAL;
467
468         callback = sd_bus_get_current_handler(call->bus);
469         if (!callback)
470                 return -EINVAL;
471
472         userdata = sd_bus_get_current_userdata(call->bus);
473
474         sender = sd_bus_message_get_sender(call);
475         if (!sender)
476                 return -EBADMSG;
477
478         c = sd_bus_message_get_allow_interactive_authorization(call);
479         if (c < 0)
480                 return c;
481         if (c > 0)
482                 interactive = true;
483
484         r = hashmap_ensure_allocated(registry, NULL);
485         if (r < 0)
486                 return r;
487
488         r = sd_bus_message_new_method_call(
489                         call->bus,
490                         &pk,
491                         "org.freedesktop.PolicyKit1",
492                         "/org/freedesktop/PolicyKit1/Authority",
493                         "org.freedesktop.PolicyKit1.Authority",
494                         "CheckAuthorization");
495         if (r < 0)
496                 return r;
497
498         r = sd_bus_message_append(
499                         pk,
500                         "(sa{sv})s",
501                         "system-bus-name", 1, "name", "s", sender,
502                         action);
503         if (r < 0)
504                 return r;
505
506         r = sd_bus_message_open_container(pk, 'a', "{ss}");
507         if (r < 0)
508                 return r;
509
510         STRV_FOREACH_PAIR(k, v, details) {
511                 r = sd_bus_message_append(pk, "{ss}", *k, *v);
512                 if (r < 0)
513                         return r;
514         }
515
516         r = sd_bus_message_close_container(pk);
517         if (r < 0)
518                 return r;
519
520         r = sd_bus_message_append(pk, "us", !!interactive, NULL);
521         if (r < 0)
522                 return r;
523
524         q = new0(AsyncPolkitQuery, 1);
525         if (!q)
526                 return -ENOMEM;
527
528         q->request = sd_bus_message_ref(call);
529         q->callback = callback;
530         q->userdata = userdata;
531
532         r = hashmap_put(*registry, call, q);
533         if (r < 0) {
534                 async_polkit_query_free(q);
535                 return r;
536         }
537
538         q->registry = *registry;
539
540         r = sd_bus_call_async(call->bus, &q->slot, pk, async_polkit_callback, q, 0);
541         if (r < 0) {
542                 async_polkit_query_free(q);
543                 return r;
544         }
545
546         return 0;
547 #endif
548
549         return -EACCES;
550 }
551
552 void bus_verify_polkit_async_registry_free(Hashmap *registry) {
553 #ifdef ENABLE_POLKIT
554         AsyncPolkitQuery *q;
555
556         while ((q = hashmap_steal_first(registry)))
557                 async_polkit_query_free(q);
558
559         hashmap_free(registry);
560 #endif
561 }
562
563 #if 0 /// UNNEEDED by elogind
564 int bus_check_peercred(sd_bus *c) {
565         struct ucred ucred;
566         socklen_t l;
567         int fd;
568
569         assert(c);
570
571         fd = sd_bus_get_fd(c);
572         if (fd < 0)
573                 return fd;
574
575         l = sizeof(struct ucred);
576         if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
577                 return -errno;
578
579         if (l != sizeof(struct ucred))
580                 return -E2BIG;
581
582         if (ucred.uid != 0 && ucred.uid != geteuid())
583                 return -EPERM;
584
585         return 1;
586 }
587
588 int bus_connect_system_systemd(sd_bus **_bus) {
589         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
590         int r;
591
592         assert(_bus);
593
594         if (geteuid() != 0)
595                 return sd_bus_default_system(_bus);
596
597         /* If we are root and kdbus is not available, then let's talk
598          * directly to the system instance, instead of going via the
599          * bus */
600
601         r = sd_bus_new(&bus);
602         if (r < 0)
603                 return r;
604
605         r = sd_bus_set_address(bus, KERNEL_SYSTEM_BUS_ADDRESS);
606         if (r < 0)
607                 return r;
608
609         bus->bus_client = true;
610
611         r = sd_bus_start(bus);
612         if (r >= 0) {
613                 *_bus = bus;
614                 bus = NULL;
615                 return 0;
616         }
617
618         bus = sd_bus_unref(bus);
619
620         r = sd_bus_new(&bus);
621         if (r < 0)
622                 return r;
623
624         r = sd_bus_set_address(bus, "unix:path=/run/systemd/private");
625         if (r < 0)
626                 return r;
627
628         r = sd_bus_start(bus);
629         if (r < 0)
630                 return sd_bus_default_system(_bus);
631
632         r = bus_check_peercred(bus);
633         if (r < 0)
634                 return r;
635
636         *_bus = bus;
637         bus = NULL;
638
639         return 0;
640 }
641
642 int bus_connect_user_systemd(sd_bus **_bus) {
643         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
644         _cleanup_free_ char *ee = NULL;
645         const char *e;
646         int r;
647
648         /* Try via kdbus first, and then directly */
649
650         assert(_bus);
651
652         r = sd_bus_new(&bus);
653         if (r < 0)
654                 return r;
655
656         if (asprintf(&bus->address, KERNEL_USER_BUS_ADDRESS_FMT, getuid()) < 0)
657                 return -ENOMEM;
658
659         bus->bus_client = true;
660
661         r = sd_bus_start(bus);
662         if (r >= 0) {
663                 *_bus = bus;
664                 bus = NULL;
665                 return 0;
666         }
667
668         bus = sd_bus_unref(bus);
669
670         e = secure_getenv("XDG_RUNTIME_DIR");
671         if (!e)
672                 return sd_bus_default_user(_bus);
673
674         ee = bus_address_escape(e);
675         if (!ee)
676                 return -ENOMEM;
677
678         r = sd_bus_new(&bus);
679         if (r < 0)
680                 return r;
681
682         bus->address = strjoin("unix:path=", ee, "/systemd/private");
683         if (!bus->address)
684                 return -ENOMEM;
685
686         r = sd_bus_start(bus);
687         if (r < 0)
688                 return sd_bus_default_user(_bus);
689
690         r = bus_check_peercred(bus);
691         if (r < 0)
692                 return r;
693
694         *_bus = bus;
695         bus = NULL;
696
697         return 0;
698 }
699 #endif // 0
700
701 #define print_property(name, fmt, ...)                                  \
702         do {                                                            \
703                 if (value)                                              \
704                         printf(fmt "\n", __VA_ARGS__);                  \
705                 else                                                    \
706                         printf("%s=" fmt "\n", name, __VA_ARGS__);      \
707         } while(0)
708
709 int bus_print_property(const char *name, sd_bus_message *property, bool value, bool all) {
710         char type;
711         const char *contents;
712         int r;
713
714         assert(name);
715         assert(property);
716
717         r = sd_bus_message_peek_type(property, &type, &contents);
718         if (r < 0)
719                 return r;
720
721         switch (type) {
722
723         case SD_BUS_TYPE_STRING: {
724                 const char *s;
725
726                 r = sd_bus_message_read_basic(property, type, &s);
727                 if (r < 0)
728                         return r;
729
730                 if (all || !isempty(s)) {
731                         _cleanup_free_ char *escaped = NULL;
732
733                         escaped = xescape(s, "\n");
734                         if (!escaped)
735                                 return -ENOMEM;
736
737                         print_property(name, "%s", escaped);
738                 }
739
740                 return 1;
741         }
742
743         case SD_BUS_TYPE_BOOLEAN: {
744                 int b;
745
746                 r = sd_bus_message_read_basic(property, type, &b);
747                 if (r < 0)
748                         return r;
749
750                 print_property(name, "%s", yes_no(b));
751
752                 return 1;
753         }
754
755         case SD_BUS_TYPE_UINT64: {
756                 uint64_t u;
757
758                 r = sd_bus_message_read_basic(property, type, &u);
759                 if (r < 0)
760                         return r;
761
762                 /* Yes, heuristics! But we can change this check
763                  * should it turn out to not be sufficient */
764
765                 if (endswith(name, "Timestamp")) {
766                         char timestamp[FORMAT_TIMESTAMP_MAX], *t;
767
768                         t = format_timestamp(timestamp, sizeof(timestamp), u);
769                         if (t || all)
770                                 print_property(name, "%s", strempty(t));
771
772                 } else if (strstr(name, "USec")) {
773                         char timespan[FORMAT_TIMESPAN_MAX];
774
775                         print_property(name, "%s", format_timespan(timespan, sizeof(timespan), u, 0));
776                 } else if (streq(name, "RestrictNamespaces")) {
777                         _cleanup_free_ char *s = NULL;
778                         const char *result = NULL;
779
780                         if ((u & NAMESPACE_FLAGS_ALL) == 0)
781                                 result = "yes";
782                         else if ((u & NAMESPACE_FLAGS_ALL) == NAMESPACE_FLAGS_ALL)
783                                 result = "no";
784                         else {
785                                 r = namespace_flag_to_string_many(u, &s);
786                                 if (r < 0)
787                                         return r;
788
789                                 result = s;
790                         }
791
792                         print_property(name, "%s", result);
793                 } else
794                         print_property(name, "%"PRIu64, u);
795
796                 return 1;
797         }
798
799         case SD_BUS_TYPE_INT64: {
800                 int64_t i;
801
802                 r = sd_bus_message_read_basic(property, type, &i);
803                 if (r < 0)
804                         return r;
805
806                 print_property(name, "%"PRIi64, i);
807
808                 return 1;
809         }
810
811         case SD_BUS_TYPE_UINT32: {
812                 uint32_t u;
813
814                 r = sd_bus_message_read_basic(property, type, &u);
815                 if (r < 0)
816                         return r;
817
818                 if (strstr(name, "UMask") || strstr(name, "Mode"))
819                         print_property(name, "%04o", u);
820                 else
821                         print_property(name, "%"PRIu32, u);
822
823                 return 1;
824         }
825
826         case SD_BUS_TYPE_INT32: {
827                 int32_t i;
828
829                 r = sd_bus_message_read_basic(property, type, &i);
830                 if (r < 0)
831                         return r;
832
833                 print_property(name, "%"PRIi32, i);
834                 return 1;
835         }
836
837         case SD_BUS_TYPE_DOUBLE: {
838                 double d;
839
840                 r = sd_bus_message_read_basic(property, type, &d);
841                 if (r < 0)
842                         return r;
843
844                 print_property(name, "%g", d);
845                 return 1;
846         }
847
848         case SD_BUS_TYPE_ARRAY:
849                 if (streq(contents, "s")) {
850                         bool first = true;
851                         const char *str;
852
853                         r = sd_bus_message_enter_container(property, SD_BUS_TYPE_ARRAY, contents);
854                         if (r < 0)
855                                 return r;
856
857                         while ((r = sd_bus_message_read_basic(property, SD_BUS_TYPE_STRING, &str)) > 0) {
858                                 _cleanup_free_ char *escaped = NULL;
859
860                                 if (first && !value)
861                                         printf("%s=", name);
862
863                                 escaped = xescape(str, "\n ");
864                                 if (!escaped)
865                                         return -ENOMEM;
866
867                                 printf("%s%s", first ? "" : " ", escaped);
868
869                                 first = false;
870                         }
871                         if (r < 0)
872                                 return r;
873
874                         if (first && all && !value)
875                                 printf("%s=", name);
876                         if (!first || all)
877                                 puts("");
878
879                         r = sd_bus_message_exit_container(property);
880                         if (r < 0)
881                                 return r;
882
883                         return 1;
884
885                 } else if (streq(contents, "y")) {
886                         const uint8_t *u;
887                         size_t n;
888
889                         r = sd_bus_message_read_array(property, SD_BUS_TYPE_BYTE, (const void**) &u, &n);
890                         if (r < 0)
891                                 return r;
892
893                         if (all || n > 0) {
894                                 unsigned int i;
895
896                                 if (!value)
897                                         printf("%s=", name);
898
899                                 for (i = 0; i < n; i++)
900                                         printf("%02x", u[i]);
901
902                                 puts("");
903                         }
904
905                         return 1;
906
907                 } else if (streq(contents, "u")) {
908                         uint32_t *u;
909                         size_t n;
910
911                         r = sd_bus_message_read_array(property, SD_BUS_TYPE_UINT32, (const void**) &u, &n);
912                         if (r < 0)
913                                 return r;
914
915                         if (all || n > 0) {
916                                 unsigned int i;
917
918                                 if (!value)
919                                         printf("%s=", name);
920
921                                 for (i = 0; i < n; i++)
922                                         printf("%08x", u[i]);
923
924                                 puts("");
925                         }
926
927                         return 1;
928                 }
929
930                 break;
931         }
932
933         return 0;
934 }
935
936 int bus_print_all_properties(sd_bus *bus, const char *dest, const char *path, char **filter, bool value, bool all) {
937         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
938         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
939         int r;
940
941         assert(bus);
942         assert(path);
943
944         r = sd_bus_call_method(bus,
945                         dest,
946                         path,
947                         "org.freedesktop.DBus.Properties",
948                         "GetAll",
949                         &error,
950                         &reply,
951                         "s", "");
952         if (r < 0)
953                 return r;
954
955         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "{sv}");
956         if (r < 0)
957                 return r;
958
959         while ((r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
960                 const char *name;
961                 const char *contents;
962
963                 r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &name);
964                 if (r < 0)
965                         return r;
966
967                 if (!filter || strv_find(filter, name)) {
968                         r = sd_bus_message_peek_type(reply, NULL, &contents);
969                         if (r < 0)
970                                 return r;
971
972                         r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_VARIANT, contents);
973                         if (r < 0)
974                                 return r;
975
976                         r = bus_print_property(name, reply, value, all);
977                         if (r < 0)
978                                 return r;
979                         if (r == 0) {
980                                 if (all)
981                                         printf("%s=[unprintable]\n", name);
982                                 /* skip what we didn't read */
983                                 r = sd_bus_message_skip(reply, contents);
984                                 if (r < 0)
985                                         return r;
986                         }
987
988                         r = sd_bus_message_exit_container(reply);
989                         if (r < 0)
990                                 return r;
991                 } else {
992                         r = sd_bus_message_skip(reply, "v");
993                         if (r < 0)
994                                 return r;
995                 }
996
997                 r = sd_bus_message_exit_container(reply);
998                 if (r < 0)
999                         return r;
1000         }
1001         if (r < 0)
1002                 return r;
1003
1004         r = sd_bus_message_exit_container(reply);
1005         if (r < 0)
1006                 return r;
1007
1008         return 0;
1009 }
1010
1011 int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1012         sd_id128_t *p = userdata;
1013         const void *v;
1014         size_t n;
1015         int r;
1016
1017         r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n);
1018         if (r < 0)
1019                 return r;
1020
1021         if (n == 0)
1022                 *p = SD_ID128_NULL;
1023         else if (n == 16)
1024                 memcpy((*p).bytes, v, n);
1025         else
1026                 return -EINVAL;
1027
1028         return 0;
1029 }
1030
1031 static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1032         char type;
1033         int r;
1034
1035         r = sd_bus_message_peek_type(m, &type, NULL);
1036         if (r < 0)
1037                 return r;
1038
1039         switch (type) {
1040
1041         case SD_BUS_TYPE_STRING: {
1042                 char **p = userdata;
1043                 const char *s;
1044
1045                 r = sd_bus_message_read_basic(m, type, &s);
1046                 if (r < 0)
1047                         return r;
1048
1049                 if (isempty(s))
1050                         s = NULL;
1051
1052                 return free_and_strdup(p, s);
1053         }
1054
1055         case SD_BUS_TYPE_ARRAY: {
1056                 _cleanup_strv_free_ char **l = NULL;
1057                 char ***p = userdata;
1058
1059                 r = bus_message_read_strv_extend(m, &l);
1060                 if (r < 0)
1061                         return r;
1062
1063                 strv_free(*p);
1064                 *p = l;
1065                 l = NULL;
1066                 return 0;
1067         }
1068
1069         case SD_BUS_TYPE_BOOLEAN: {
1070                 unsigned b;
1071                 int *p = userdata;
1072
1073                 r = sd_bus_message_read_basic(m, type, &b);
1074                 if (r < 0)
1075                         return r;
1076
1077                 *p = b;
1078                 return 0;
1079         }
1080
1081         case SD_BUS_TYPE_INT32:
1082         case SD_BUS_TYPE_UINT32: {
1083                 uint32_t u, *p = userdata;
1084
1085                 r = sd_bus_message_read_basic(m, type, &u);
1086                 if (r < 0)
1087                         return r;
1088
1089                 *p = u;
1090                 return 0;
1091         }
1092
1093         case SD_BUS_TYPE_INT64:
1094         case SD_BUS_TYPE_UINT64: {
1095                 uint64_t t, *p = userdata;
1096
1097                 r = sd_bus_message_read_basic(m, type, &t);
1098                 if (r < 0)
1099                         return r;
1100
1101                 *p = t;
1102                 return 0;
1103         }
1104
1105         case SD_BUS_TYPE_DOUBLE: {
1106                 double d, *p = userdata;
1107
1108                 r = sd_bus_message_read_basic(m, type, &d);
1109                 if (r < 0)
1110                         return r;
1111
1112                 *p = d;
1113                 return 0;
1114         }}
1115
1116         return -EOPNOTSUPP;
1117 }
1118
1119 int bus_message_map_all_properties(
1120                 sd_bus_message *m,
1121                 const struct bus_properties_map *map,
1122                 void *userdata) {
1123
1124         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1125         int r;
1126
1127         assert(m);
1128         assert(map);
1129
1130         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
1131         if (r < 0)
1132                 return r;
1133
1134         while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1135                 const struct bus_properties_map *prop;
1136                 const char *member;
1137                 const char *contents;
1138                 void *v;
1139                 unsigned i;
1140
1141                 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
1142                 if (r < 0)
1143                         return r;
1144
1145                 for (i = 0, prop = NULL; map[i].member; i++)
1146                         if (streq(map[i].member, member)) {
1147                                 prop = &map[i];
1148                                 break;
1149                         }
1150
1151                 if (prop) {
1152                         r = sd_bus_message_peek_type(m, NULL, &contents);
1153                         if (r < 0)
1154                                 return r;
1155
1156                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
1157                         if (r < 0)
1158                                 return r;
1159
1160                         v = (uint8_t *)userdata + prop->offset;
1161                         if (map[i].set)
1162                                 r = prop->set(sd_bus_message_get_bus(m), member, m, &error, v);
1163                         else
1164                                 r = map_basic(sd_bus_message_get_bus(m), member, m, &error, v);
1165                         if (r < 0)
1166                                 return r;
1167
1168                         r = sd_bus_message_exit_container(m);
1169                         if (r < 0)
1170                                 return r;
1171                 } else {
1172                         r = sd_bus_message_skip(m, "v");
1173                         if (r < 0)
1174                                 return r;
1175                 }
1176
1177                 r = sd_bus_message_exit_container(m);
1178                 if (r < 0)
1179                         return r;
1180         }
1181         if (r < 0)
1182                 return r;
1183
1184         return sd_bus_message_exit_container(m);
1185 }
1186
1187 #if 0 /// UNNEEDED by elogind
1188 int bus_message_map_properties_changed(
1189                 sd_bus_message *m,
1190                 const struct bus_properties_map *map,
1191                 void *userdata) {
1192
1193         const char *member;
1194         int r, invalidated, i;
1195
1196         assert(m);
1197         assert(map);
1198
1199         r = bus_message_map_all_properties(m, map, userdata);
1200         if (r < 0)
1201                 return r;
1202
1203         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s");
1204         if (r < 0)
1205                 return r;
1206
1207         invalidated = 0;
1208         while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0)
1209                 for (i = 0; map[i].member; i++)
1210                         if (streq(map[i].member, member)) {
1211                                 ++invalidated;
1212                                 break;
1213                         }
1214         if (r < 0)
1215                 return r;
1216
1217         r = sd_bus_message_exit_container(m);
1218         if (r < 0)
1219                 return r;
1220
1221         return invalidated;
1222 }
1223 #endif // 0
1224
1225 int bus_map_all_properties(
1226                 sd_bus *bus,
1227                 const char *destination,
1228                 const char *path,
1229                 const struct bus_properties_map *map,
1230                 void *userdata) {
1231
1232         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1233         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1234         int r;
1235
1236         assert(bus);
1237         assert(destination);
1238         assert(path);
1239         assert(map);
1240
1241         r = sd_bus_call_method(
1242                         bus,
1243                         destination,
1244                         path,
1245                         "org.freedesktop.DBus.Properties",
1246                         "GetAll",
1247                         &error,
1248                         &m,
1249                         "s", "");
1250         if (r < 0)
1251                 return r;
1252
1253         return bus_message_map_all_properties(m, map, userdata);
1254 }
1255
1256 int bus_connect_transport(BusTransport transport, const char *host, bool user, sd_bus **ret) {
1257         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1258         int r;
1259
1260         assert(transport >= 0);
1261         assert(transport < _BUS_TRANSPORT_MAX);
1262         assert(ret);
1263
1264         assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1265         assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1266
1267         switch (transport) {
1268
1269         case BUS_TRANSPORT_LOCAL:
1270 #if 0 /// elogind does not support a user bus
1271                 if (user)
1272                         r = sd_bus_default_user(&bus);
1273                 else
1274 #endif // 0
1275                         r = sd_bus_default_system(&bus);
1276
1277                 break;
1278
1279         case BUS_TRANSPORT_REMOTE:
1280                 r = sd_bus_open_system_remote(&bus, host);
1281                 break;
1282
1283         case BUS_TRANSPORT_MACHINE:
1284                 r = sd_bus_open_system_machine(&bus, host);
1285                 break;
1286
1287         default:
1288                 assert_not_reached("Hmm, unknown transport type.");
1289         }
1290         if (r < 0)
1291                 return r;
1292
1293         r = sd_bus_set_exit_on_disconnect(bus, true);
1294         if (r < 0)
1295                 return r;
1296
1297         *ret = bus;
1298         bus = NULL;
1299
1300         return 0;
1301 }
1302
1303 #if 0 /// UNNEEDED by elogind
1304 int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1305         int r;
1306
1307         assert(transport >= 0);
1308         assert(transport < _BUS_TRANSPORT_MAX);
1309         assert(bus);
1310
1311         assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1312         assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1313
1314         switch (transport) {
1315
1316         case BUS_TRANSPORT_LOCAL:
1317                 if (user)
1318                         r = bus_connect_user_systemd(bus);
1319                 else
1320                         r = bus_connect_system_systemd(bus);
1321
1322                 break;
1323
1324         case BUS_TRANSPORT_REMOTE:
1325                 r = sd_bus_open_system_remote(bus, host);
1326                 break;
1327
1328         case BUS_TRANSPORT_MACHINE:
1329                 r = sd_bus_open_system_machine(bus, host);
1330                 break;
1331
1332         default:
1333                 assert_not_reached("Hmm, unknown transport type.");
1334         }
1335
1336         return r;
1337 }
1338 #endif // 0
1339
1340 int bus_property_get_bool(
1341                 sd_bus *bus,
1342                 const char *path,
1343                 const char *interface,
1344                 const char *property,
1345                 sd_bus_message *reply,
1346                 void *userdata,
1347                 sd_bus_error *error) {
1348
1349         int b = *(bool*) userdata;
1350
1351         return sd_bus_message_append_basic(reply, 'b', &b);
1352 }
1353
1354 #if 0 /// UNNEEDED by elogind
1355 int bus_property_get_id128(
1356                 sd_bus *bus,
1357                 const char *path,
1358                 const char *interface,
1359                 const char *property,
1360                 sd_bus_message *reply,
1361                 void *userdata,
1362                 sd_bus_error *error) {
1363
1364         sd_id128_t *id = userdata;
1365
1366         if (sd_id128_is_null(*id)) /* Add an empty array if the ID is zero */
1367                 return sd_bus_message_append(reply, "ay", 0);
1368         else
1369                 return sd_bus_message_append_array(reply, 'y', id->bytes, 16);
1370 }
1371 #endif // 0
1372
1373 #if __SIZEOF_SIZE_T__ != 8
1374 int bus_property_get_size(
1375                 sd_bus *bus,
1376                 const char *path,
1377                 const char *interface,
1378                 const char *property,
1379                 sd_bus_message *reply,
1380                 void *userdata,
1381                 sd_bus_error *error) {
1382
1383         uint64_t sz = *(size_t*) userdata;
1384
1385         return sd_bus_message_append_basic(reply, 't', &sz);
1386 }
1387 #endif
1388
1389 #if __SIZEOF_LONG__ != 8
1390 int bus_property_get_long(
1391                 sd_bus *bus,
1392                 const char *path,
1393                 const char *interface,
1394                 const char *property,
1395                 sd_bus_message *reply,
1396                 void *userdata,
1397                 sd_bus_error *error) {
1398
1399         int64_t l = *(long*) userdata;
1400
1401         return sd_bus_message_append_basic(reply, 'x', &l);
1402 }
1403
1404 int bus_property_get_ulong(
1405                 sd_bus *bus,
1406                 const char *path,
1407                 const char *interface,
1408                 const char *property,
1409                 sd_bus_message *reply,
1410                 void *userdata,
1411                 sd_bus_error *error) {
1412
1413         uint64_t ul = *(unsigned long*) userdata;
1414
1415         return sd_bus_message_append_basic(reply, 't', &ul);
1416 }
1417 #endif
1418
1419 int bus_log_parse_error(int r) {
1420         return log_error_errno(r, "Failed to parse bus message: %m");
1421 }
1422
1423 #if 0 /// UNNEEDED by elogind
1424 int bus_log_create_error(int r) {
1425         return log_error_errno(r, "Failed to create bus message: %m");
1426 }
1427
1428 #endif // 0
1429 #if 0 /// UNNEEDED by elogind
1430 /**
1431  * bus_path_encode_unique() - encode unique object path
1432  * @b: bus connection or NULL
1433  * @prefix: object path prefix
1434  * @sender_id: unique-name of client, or NULL
1435  * @external_id: external ID to be chosen by client, or NULL
1436  * @ret_path: storage for encoded object path pointer
1437  *
1438  * Whenever we provide a bus API that allows clients to create and manage
1439  * server-side objects, we need to provide a unique name for these objects. If
1440  * we let the server choose the name, we suffer from a race condition: If a
1441  * client creates an object asynchronously, it cannot destroy that object until
1442  * it received the method reply. It cannot know the name of the new object,
1443  * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
1444  *
1445  * Therefore, many APIs allow the client to choose the unique name for newly
1446  * created objects. There're two problems to solve, though:
1447  *    1) Object names are usually defined via dbus object paths, which are
1448  *       usually globally namespaced. Therefore, multiple clients must be able
1449  *       to choose unique object names without interference.
1450  *    2) If multiple libraries share the same bus connection, they must be
1451  *       able to choose unique object names without interference.
1452  * The first problem is solved easily by prefixing a name with the
1453  * unique-bus-name of a connection. The server side must enforce this and
1454  * reject any other name. The second problem is solved by providing unique
1455  * suffixes from within sd-bus.
1456  *
1457  * This helper allows clients to create unique object-paths. It uses the
1458  * template '/prefix/sender_id/external_id' and returns the new path in
1459  * @ret_path (must be freed by the caller).
1460  * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
1461  * NULL, this function allocates a unique suffix via @b (by requesting a new
1462  * cookie). If both @sender_id and @external_id are given, @b can be passed as
1463  * NULL.
1464  *
1465  * Returns: 0 on success, negative error code on failure.
1466  */
1467 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
1468         _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
1469         char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
1470         int r;
1471
1472         assert_return(b || (sender_id && external_id), -EINVAL);
1473         assert_return(object_path_is_valid(prefix), -EINVAL);
1474         assert_return(ret_path, -EINVAL);
1475
1476         if (!sender_id) {
1477                 r = sd_bus_get_unique_name(b, &sender_id);
1478                 if (r < 0)
1479                         return r;
1480         }
1481
1482         if (!external_id) {
1483                 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
1484                 external_id = external_buf;
1485         }
1486
1487         sender_label = bus_label_escape(sender_id);
1488         if (!sender_label)
1489                 return -ENOMEM;
1490
1491         external_label = bus_label_escape(external_id);
1492         if (!external_label)
1493                 return -ENOMEM;
1494
1495         p = strjoin(prefix, "/", sender_label, "/", external_label);
1496         if (!p)
1497                 return -ENOMEM;
1498
1499         *ret_path = p;
1500         return 0;
1501 }
1502
1503 /**
1504  * bus_path_decode_unique() - decode unique object path
1505  * @path: object path to decode
1506  * @prefix: object path prefix
1507  * @ret_sender: output parameter for sender-id label
1508  * @ret_external: output parameter for external-id label
1509  *
1510  * This does the reverse of bus_path_encode_unique() (see its description for
1511  * details). Both trailing labels, sender-id and external-id, are unescaped and
1512  * returned in the given output parameters (the caller must free them).
1513  *
1514  * Note that this function returns 0 if the path does not match the template
1515  * (see bus_path_encode_unique()), 1 if it matched.
1516  *
1517  * Returns: Negative error code on failure, 0 if the given object path does not
1518  *          match the template (return parameters are set to NULL), 1 if it was
1519  *          parsed successfully (return parameters contain allocated labels).
1520  */
1521 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
1522         const char *p, *q;
1523         char *sender, *external;
1524
1525         assert(object_path_is_valid(path));
1526         assert(object_path_is_valid(prefix));
1527         assert(ret_sender);
1528         assert(ret_external);
1529
1530         p = object_path_startswith(path, prefix);
1531         if (!p) {
1532                 *ret_sender = NULL;
1533                 *ret_external = NULL;
1534                 return 0;
1535         }
1536
1537         q = strchr(p, '/');
1538         if (!q) {
1539                 *ret_sender = NULL;
1540                 *ret_external = NULL;
1541                 return 0;
1542         }
1543
1544         sender = bus_label_unescape_n(p, q - p);
1545         external = bus_label_unescape(q + 1);
1546         if (!sender || !external) {
1547                 free(sender);
1548                 free(external);
1549                 return -ENOMEM;
1550         }
1551
1552         *ret_sender = sender;
1553         *ret_external = external;
1554         return 1;
1555 }
1556 #endif // 0
1557
1558 #if 0 /// UNNEEDED by elogind
1559 int bus_property_get_rlimit(
1560                 sd_bus *bus,
1561                 const char *path,
1562                 const char *interface,
1563                 const char *property,
1564                 sd_bus_message *reply,
1565                 void *userdata,
1566                 sd_bus_error *error) {
1567
1568         struct rlimit *rl;
1569         uint64_t u;
1570         rlim_t x;
1571         const char *is_soft;
1572
1573         assert(bus);
1574         assert(reply);
1575         assert(userdata);
1576
1577         is_soft = endswith(property, "Soft");
1578         rl = *(struct rlimit**) userdata;
1579         if (rl)
1580                 x = is_soft ? rl->rlim_cur : rl->rlim_max;
1581         else {
1582                 struct rlimit buf = {};
1583                 int z;
1584                 const char *s;
1585
1586                 s = is_soft ? strndupa(property, is_soft - property) : property;
1587
1588                 z = rlimit_from_string(strstr(s, "Limit"));
1589                 assert(z >= 0);
1590
1591                 getrlimit(z, &buf);
1592                 x = is_soft ? buf.rlim_cur : buf.rlim_max;
1593         }
1594
1595         /* rlim_t might have different sizes, let's map
1596          * RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on
1597          * all archs */
1598         u = x == RLIM_INFINITY ? (uint64_t) -1 : (uint64_t) x;
1599
1600         return sd_bus_message_append(reply, "t", u);
1601 }
1602 #endif // 0
1603
1604 int bus_track_add_name_many(sd_bus_track *t, char **l) {
1605         int r = 0;
1606         char **i;
1607
1608         assert(t);
1609
1610         /* Continues adding after failure, and returns the first failure. */
1611
1612         STRV_FOREACH(i, l) {
1613                 int k;
1614
1615                 k = sd_bus_track_add_name(t, *i);
1616                 if (k < 0 && r >= 0)
1617                         r = k;
1618         }
1619
1620         return r;
1621 }