chiark / gitweb /
d2768d62bb61bc7da7fb806afdf96f5de50be26e
[elogind.git] / src / shared / bus-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   This file is part of systemd.
4
5   Copyright 2013 Lennart Poettering
6 ***/
7
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <inttypes.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/ioctl.h>
15 #include <sys/resource.h>
16 #include <sys/socket.h>
17 #include <unistd.h>
18
19 #include "sd-bus-protocol.h"
20 #include "sd-bus.h"
21 #include "sd-daemon.h"
22 #include "sd-event.h"
23 #include "sd-id128.h"
24
25 #include "alloc-util.h"
26 #include "bus-internal.h"
27 #include "bus-label.h"
28 #include "bus-message.h"
29 #include "bus-util.h"
30 #include "cap-list.h"
31 #include "cgroup-util.h"
32 #include "def.h"
33 #include "escape.h"
34 #include "fd-util.h"
35 #include "missing.h"
36 #include "mount-util.h"
37 #include "nsflags.h"
38 #include "parse-util.h"
39 #include "proc-cmdline.h"
40 //#include "rlimit-util.h"
41 #include "stdio-util.h"
42 #include "strv.h"
43 #include "user-util.h"
44
45 #if 0 /// UNNEEDED by elogind
46 static int name_owner_change_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
47         sd_event *e = userdata;
48
49         assert(m);
50         assert(e);
51
52         sd_bus_close(sd_bus_message_get_bus(m));
53         sd_event_exit(e, 0);
54
55         return 1;
56 }
57
58 int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name) {
59         const char *match;
60         const char *unique;
61         int r;
62
63         assert(e);
64         assert(bus);
65         assert(name);
66
67         /* We unregister the name here and then wait for the
68          * NameOwnerChanged signal for this event to arrive before we
69          * quit. We do this in order to make sure that any queued
70          * requests are still processed before we really exit. */
71
72         r = sd_bus_get_unique_name(bus, &unique);
73         if (r < 0)
74                 return r;
75
76         match = strjoina(
77                         "sender='org.freedesktop.DBus',"
78                         "type='signal',"
79                         "interface='org.freedesktop.DBus',"
80                         "member='NameOwnerChanged',"
81                         "path='/org/freedesktop/DBus',"
82                         "arg0='", name, "',",
83                         "arg1='", unique, "',",
84                         "arg2=''");
85
86         r = sd_bus_add_match_async(bus, NULL, match, name_owner_change_callback, NULL, e);
87         if (r < 0)
88                 return r;
89
90         r = sd_bus_release_name_async(bus, NULL, name, NULL, NULL);
91         if (r < 0)
92                 return r;
93
94         return 0;
95 }
96
97 int bus_event_loop_with_idle(
98                 sd_event *e,
99                 sd_bus *bus,
100                 const char *name,
101                 usec_t timeout,
102                 check_idle_t check_idle,
103                 void *userdata) {
104         bool exiting = false;
105         int r, code;
106
107         assert(e);
108         assert(bus);
109         assert(name);
110
111         for (;;) {
112                 bool idle;
113
114                 r = sd_event_get_state(e);
115                 if (r < 0)
116                         return r;
117                 if (r == SD_EVENT_FINISHED)
118                         break;
119
120                 if (check_idle)
121                         idle = check_idle(userdata);
122                 else
123                         idle = true;
124
125                 r = sd_event_run(e, exiting || !idle ? (uint64_t) -1 : timeout);
126                 if (r < 0)
127                         return r;
128
129                 if (r == 0 && !exiting && idle) {
130
131                         r = sd_bus_try_close(bus);
132                         if (r == -EBUSY)
133                                 continue;
134
135                         /* Fallback for dbus1 connections: we
136                          * unregister the name and wait for the
137                          * response to come through for it */
138                         if (r == -EOPNOTSUPP) {
139
140                                 /* Inform the service manager that we
141                                  * are going down, so that it will
142                                  * queue all further start requests,
143                                  * instead of assuming we are already
144                                  * running. */
145                                 sd_notify(false, "STOPPING=1");
146
147                                 r = bus_async_unregister_and_exit(e, bus, name);
148                                 if (r < 0)
149                                         return r;
150
151                                 exiting = true;
152                                 continue;
153                         }
154
155                         if (r < 0)
156                                 return r;
157
158                         sd_event_exit(e, 0);
159                         break;
160                 }
161         }
162
163         r = sd_event_get_exit_code(e, &code);
164         if (r < 0)
165                 return r;
166
167         return code;
168 }
169 #endif // 0
170
171 int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error) {
172         _cleanup_(sd_bus_message_unrefp) sd_bus_message *rep = NULL;
173         int r, has_owner = 0;
174
175         assert(c);
176         assert(name);
177
178         r = sd_bus_call_method(c,
179                                "org.freedesktop.DBus",
180                                "/org/freedesktop/dbus",
181                                "org.freedesktop.DBus",
182                                "NameHasOwner",
183                                error,
184                                &rep,
185                                "s",
186                                name);
187         if (r < 0)
188                 return r;
189
190         r = sd_bus_message_read_basic(rep, 'b', &has_owner);
191         if (r < 0)
192                 return sd_bus_error_set_errno(error, r);
193
194         return has_owner;
195 }
196
197 static int check_good_user(sd_bus_message *m, uid_t good_user) {
198         _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
199         uid_t sender_uid;
200         int r;
201
202         assert(m);
203
204         if (good_user == UID_INVALID)
205                 return 0;
206
207         r = sd_bus_query_sender_creds(m, SD_BUS_CREDS_EUID, &creds);
208         if (r < 0)
209                 return r;
210
211         /* Don't trust augmented credentials for authorization */
212         assert_return((sd_bus_creds_get_augmented_mask(creds) & SD_BUS_CREDS_EUID) == 0, -EPERM);
213
214         r = sd_bus_creds_get_euid(creds, &sender_uid);
215         if (r < 0)
216                 return r;
217
218         return sender_uid == good_user;
219 }
220
221 int bus_test_polkit(
222                 sd_bus_message *call,
223                 int capability,
224                 const char *action,
225                 const char **details,
226                 uid_t good_user,
227                 bool *_challenge,
228                 sd_bus_error *e) {
229
230         int r;
231
232         assert(call);
233         assert(action);
234
235         /* Tests non-interactively! */
236
237         r = check_good_user(call, good_user);
238         if (r != 0)
239                 return r;
240
241         r = sd_bus_query_sender_privilege(call, capability);
242         if (r < 0)
243                 return r;
244         else if (r > 0)
245                 return 1;
246 #if ENABLE_POLKIT
247         else {
248                 _cleanup_(sd_bus_message_unrefp) sd_bus_message *request = NULL;
249                 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
250                 int authorized = false, challenge = false;
251                 const char *sender, **k, **v;
252
253                 sender = sd_bus_message_get_sender(call);
254                 if (!sender)
255                         return -EBADMSG;
256
257                 r = sd_bus_message_new_method_call(
258                                 call->bus,
259                                 &request,
260                                 "org.freedesktop.PolicyKit1",
261                                 "/org/freedesktop/PolicyKit1/Authority",
262                                 "org.freedesktop.PolicyKit1.Authority",
263                                 "CheckAuthorization");
264                 if (r < 0)
265                         return r;
266
267                 r = sd_bus_message_append(
268                                 request,
269                                 "(sa{sv})s",
270                                 "system-bus-name", 1, "name", "s", sender,
271                                 action);
272                 if (r < 0)
273                         return r;
274
275                 r = sd_bus_message_open_container(request, 'a', "{ss}");
276                 if (r < 0)
277                         return r;
278
279                 STRV_FOREACH_PAIR(k, v, details) {
280                         r = sd_bus_message_append(request, "{ss}", *k, *v);
281                         if (r < 0)
282                                 return r;
283                 }
284
285                 r = sd_bus_message_close_container(request);
286                 if (r < 0)
287                         return r;
288
289                 r = sd_bus_message_append(request, "us", 0, NULL);
290                 if (r < 0)
291                         return r;
292
293                 r = sd_bus_call(call->bus, request, 0, e, &reply);
294                 if (r < 0) {
295                         /* Treat no PK available as access denied */
296                         if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN)) {
297                                 sd_bus_error_free(e);
298                                 return -EACCES;
299                         }
300
301                         return r;
302                 }
303
304                 r = sd_bus_message_enter_container(reply, 'r', "bba{ss}");
305                 if (r < 0)
306                         return r;
307
308                 r = sd_bus_message_read(reply, "bb", &authorized, &challenge);
309                 if (r < 0)
310                         return r;
311
312                 if (authorized)
313                         return 1;
314
315                 if (_challenge) {
316                         *_challenge = challenge;
317                         return 0;
318                 }
319         }
320 #endif
321
322         return -EACCES;
323 }
324
325 #if ENABLE_POLKIT
326
327 typedef struct AsyncPolkitQuery {
328         sd_bus_message *request, *reply;
329         sd_bus_message_handler_t callback;
330         void *userdata;
331         sd_bus_slot *slot;
332         Hashmap *registry;
333 } AsyncPolkitQuery;
334
335 static void async_polkit_query_free(AsyncPolkitQuery *q) {
336
337         if (!q)
338                 return;
339
340         sd_bus_slot_unref(q->slot);
341
342         if (q->registry && q->request)
343                 hashmap_remove(q->registry, q->request);
344
345         sd_bus_message_unref(q->request);
346         sd_bus_message_unref(q->reply);
347
348         free(q);
349 }
350
351 static int async_polkit_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
352         _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
353         AsyncPolkitQuery *q = userdata;
354         int r;
355
356         assert(reply);
357         assert(q);
358
359         q->slot = sd_bus_slot_unref(q->slot);
360         q->reply = sd_bus_message_ref(reply);
361
362         r = sd_bus_message_rewind(q->request, true);
363         if (r < 0) {
364                 r = sd_bus_reply_method_errno(q->request, r, NULL);
365                 goto finish;
366         }
367
368         r = q->callback(q->request, q->userdata, &error_buffer);
369         r = bus_maybe_reply_error(q->request, r, &error_buffer);
370
371 finish:
372         async_polkit_query_free(q);
373
374         return r;
375 }
376
377 #endif
378
379 int bus_verify_polkit_async(
380                 sd_bus_message *call,
381                 int capability,
382                 const char *action,
383                 const char **details,
384                 bool interactive,
385                 uid_t good_user,
386                 Hashmap **registry,
387                 sd_bus_error *error) {
388
389 #if ENABLE_POLKIT
390         _cleanup_(sd_bus_message_unrefp) sd_bus_message *pk = NULL;
391         AsyncPolkitQuery *q;
392         const char *sender, **k, **v;
393         sd_bus_message_handler_t callback;
394         void *userdata;
395         int c;
396 #endif
397         int r;
398
399         assert(call);
400         assert(action);
401         assert(registry);
402
403         r = check_good_user(call, good_user);
404         if (r != 0)
405                 return r;
406
407 #if ENABLE_POLKIT
408         q = hashmap_get(*registry, call);
409         if (q) {
410                 int authorized, challenge;
411
412                 /* This is the second invocation of this function, and
413                  * there's already a response from polkit, let's
414                  * process it */
415                 assert(q->reply);
416
417                 if (sd_bus_message_is_method_error(q->reply, NULL)) {
418                         const sd_bus_error *e;
419
420                         /* Copy error from polkit reply */
421                         e = sd_bus_message_get_error(q->reply);
422                         sd_bus_error_copy(error, e);
423
424                         /* Treat no PK available as access denied */
425                         if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN))
426                                 return -EACCES;
427
428                         return -sd_bus_error_get_errno(e);
429                 }
430
431                 r = sd_bus_message_enter_container(q->reply, 'r', "bba{ss}");
432                 if (r >= 0)
433                         r = sd_bus_message_read(q->reply, "bb", &authorized, &challenge);
434
435                 if (r < 0)
436                         return r;
437
438                 if (authorized)
439                         return 1;
440
441                 if (challenge)
442                         return sd_bus_error_set(error, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED, "Interactive authentication required.");
443
444                 return -EACCES;
445         }
446 #endif
447
448         r = sd_bus_query_sender_privilege(call, capability);
449         if (r < 0)
450                 return r;
451         else if (r > 0)
452                 return 1;
453
454 #if ENABLE_POLKIT
455         if (sd_bus_get_current_message(call->bus) != call)
456                 return -EINVAL;
457
458         callback = sd_bus_get_current_handler(call->bus);
459         if (!callback)
460                 return -EINVAL;
461
462         userdata = sd_bus_get_current_userdata(call->bus);
463
464         sender = sd_bus_message_get_sender(call);
465         if (!sender)
466                 return -EBADMSG;
467
468         c = sd_bus_message_get_allow_interactive_authorization(call);
469         if (c < 0)
470                 return c;
471         if (c > 0)
472                 interactive = true;
473
474         r = hashmap_ensure_allocated(registry, NULL);
475         if (r < 0)
476                 return r;
477
478         r = sd_bus_message_new_method_call(
479                         call->bus,
480                         &pk,
481                         "org.freedesktop.PolicyKit1",
482                         "/org/freedesktop/PolicyKit1/Authority",
483                         "org.freedesktop.PolicyKit1.Authority",
484                         "CheckAuthorization");
485         if (r < 0)
486                 return r;
487
488         r = sd_bus_message_append(
489                         pk,
490                         "(sa{sv})s",
491                         "system-bus-name", 1, "name", "s", sender,
492                         action);
493         if (r < 0)
494                 return r;
495
496         r = sd_bus_message_open_container(pk, 'a', "{ss}");
497         if (r < 0)
498                 return r;
499
500         STRV_FOREACH_PAIR(k, v, details) {
501                 r = sd_bus_message_append(pk, "{ss}", *k, *v);
502                 if (r < 0)
503                         return r;
504         }
505
506         r = sd_bus_message_close_container(pk);
507         if (r < 0)
508                 return r;
509
510         r = sd_bus_message_append(pk, "us", !!interactive, NULL);
511         if (r < 0)
512                 return r;
513
514         q = new0(AsyncPolkitQuery, 1);
515         if (!q)
516                 return -ENOMEM;
517
518         q->request = sd_bus_message_ref(call);
519         q->callback = callback;
520         q->userdata = userdata;
521
522         r = hashmap_put(*registry, call, q);
523         if (r < 0) {
524                 async_polkit_query_free(q);
525                 return r;
526         }
527
528         q->registry = *registry;
529
530         r = sd_bus_call_async(call->bus, &q->slot, pk, async_polkit_callback, q, 0);
531         if (r < 0) {
532                 async_polkit_query_free(q);
533                 return r;
534         }
535
536         return 0;
537 #endif
538
539         return -EACCES;
540 }
541
542 void bus_verify_polkit_async_registry_free(Hashmap *registry) {
543 #if ENABLE_POLKIT
544         hashmap_free_with_destructor(registry, async_polkit_query_free);
545 #endif
546 }
547
548 #if 0 /// UNNEEDED by elogind
549 int bus_check_peercred(sd_bus *c) {
550         struct ucred ucred;
551         int fd, r;
552
553         assert(c);
554
555         fd = sd_bus_get_fd(c);
556         if (fd < 0)
557                 return fd;
558
559         r = getpeercred(fd, &ucred);
560         if (r < 0)
561                 return r;
562
563         if (ucred.uid != 0 && ucred.uid != geteuid())
564                 return -EPERM;
565
566         return 1;
567 }
568
569 int bus_connect_system_systemd(sd_bus **_bus) {
570         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
571         int r;
572
573         assert(_bus);
574
575         if (geteuid() != 0)
576                 return sd_bus_default_system(_bus);
577
578         /* If we are root then let's talk directly to the system
579          * instance, instead of going via the bus */
580
581         r = sd_bus_new(&bus);
582         if (r < 0)
583                 return r;
584
585         r = sd_bus_set_address(bus, "unix:path=/run/systemd/private");
586         if (r < 0)
587                 return r;
588
589         r = sd_bus_start(bus);
590         if (r < 0)
591                 return sd_bus_default_system(_bus);
592
593         r = bus_check_peercred(bus);
594         if (r < 0)
595                 return r;
596
597         *_bus = TAKE_PTR(bus);
598
599         return 0;
600 }
601
602 int bus_connect_user_systemd(sd_bus **_bus) {
603         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
604         _cleanup_free_ char *ee = NULL;
605         const char *e;
606         int r;
607
608         assert(_bus);
609
610         e = secure_getenv("XDG_RUNTIME_DIR");
611         if (!e)
612                 return sd_bus_default_user(_bus);
613
614         ee = bus_address_escape(e);
615         if (!ee)
616                 return -ENOMEM;
617
618         r = sd_bus_new(&bus);
619         if (r < 0)
620                 return r;
621
622         bus->address = strjoin("unix:path=", ee, "/systemd/private");
623         if (!bus->address)
624                 return -ENOMEM;
625
626         r = sd_bus_start(bus);
627         if (r < 0)
628                 return sd_bus_default_user(_bus);
629
630         r = bus_check_peercred(bus);
631         if (r < 0)
632                 return r;
633
634         *_bus = TAKE_PTR(bus);
635
636         return 0;
637 }
638 #endif // 0
639
640 #define print_property(name, fmt, ...)                                  \
641         do {                                                            \
642                 if (value)                                              \
643                         printf(fmt "\n", __VA_ARGS__);                  \
644                 else                                                    \
645                         printf("%s=" fmt "\n", name, __VA_ARGS__);      \
646         } while (0)
647
648 int bus_print_property(const char *name, sd_bus_message *m, bool value, bool all) {
649         char type;
650         const char *contents;
651         int r;
652
653         assert(name);
654         assert(m);
655
656         r = sd_bus_message_peek_type(m, &type, &contents);
657         if (r < 0)
658                 return r;
659
660         switch (type) {
661
662         case SD_BUS_TYPE_STRING: {
663                 const char *s;
664
665                 r = sd_bus_message_read_basic(m, type, &s);
666                 if (r < 0)
667                         return r;
668
669                 if (all || !isempty(s)) {
670                         bool good;
671
672                         /* This property has a single value, so we need to take
673                          * care not to print a new line, everything else is OK. */
674                         good = !strchr(s, '\n');
675                         print_property(name, "%s", good ? s : "[unprintable]");
676                 }
677
678                 return 1;
679         }
680
681         case SD_BUS_TYPE_BOOLEAN: {
682                 int b;
683
684                 r = sd_bus_message_read_basic(m, type, &b);
685                 if (r < 0)
686                         return r;
687
688                 print_property(name, "%s", yes_no(b));
689
690                 return 1;
691         }
692
693         case SD_BUS_TYPE_UINT64: {
694                 uint64_t u;
695
696                 r = sd_bus_message_read_basic(m, type, &u);
697                 if (r < 0)
698                         return r;
699
700                 /* Yes, heuristics! But we can change this check
701                  * should it turn out to not be sufficient */
702
703                 if (endswith(name, "Timestamp") ||
704                     STR_IN_SET(name, "NextElapseUSecRealtime", "LastTriggerUSec", "TimeUSec", "RTCTimeUSec")) {
705                         char timestamp[FORMAT_TIMESTAMP_MAX];
706                         const char *t;
707
708                         t = format_timestamp(timestamp, sizeof(timestamp), u);
709                         if (t || all)
710                                 print_property(name, "%s", strempty(t));
711
712                 } else if (strstr(name, "USec")) {
713                         char timespan[FORMAT_TIMESPAN_MAX];
714
715                         print_property(name, "%s", format_timespan(timespan, sizeof(timespan), u, 0));
716                 } else if (streq(name, "RestrictNamespaces")) {
717                         _cleanup_free_ char *s = NULL;
718                         const char *result;
719
720                         if ((u & NAMESPACE_FLAGS_ALL) == 0)
721                                 result = "yes";
722                         else if ((u & NAMESPACE_FLAGS_ALL) == NAMESPACE_FLAGS_ALL)
723                                 result = "no";
724                         else {
725                                 r = namespace_flags_to_string(u, &s);
726                                 if (r < 0)
727                                         return r;
728
729                                 result = s;
730                         }
731
732                         print_property(name, "%s", result);
733
734                 } else if (streq(name, "MountFlags")) {
735                         const char *result;
736
737                         result = mount_propagation_flags_to_string(u);
738                         if (!result)
739                                 return -EINVAL;
740
741                         print_property(name, "%s", result);
742
743                 } else if (STR_IN_SET(name, "CapabilityBoundingSet", "AmbientCapabilities")) {
744                         _cleanup_free_ char *s = NULL;
745
746                         r = capability_set_to_string_alloc(u, &s);
747                         if (r < 0)
748                                 return r;
749
750                         print_property(name, "%s", s);
751
752                 } else if ((STR_IN_SET(name, "CPUWeight", "StartupCPUWeight", "IOWeight", "StartupIOWeight") && u == CGROUP_WEIGHT_INVALID) ||
753                            (STR_IN_SET(name, "CPUShares", "StartupCPUShares") && u == CGROUP_CPU_SHARES_INVALID) ||
754                            (STR_IN_SET(name, "BlockIOWeight", "StartupBlockIOWeight") && u == CGROUP_BLKIO_WEIGHT_INVALID) ||
755                            (STR_IN_SET(name, "MemoryCurrent", "TasksCurrent") && u == (uint64_t) -1) ||
756                            (endswith(name, "NSec") && u == (uint64_t) -1))
757
758                         print_property(name, "%s", "[not set]");
759
760                 else if ((STR_IN_SET(name, "MemoryLow", "MemoryHigh", "MemoryMax", "MemorySwapMax", "MemoryLimit") && u == CGROUP_LIMIT_MAX) ||
761                          (STR_IN_SET(name, "TasksMax", "DefaultTasksMax") && u == (uint64_t) -1) ||
762                          (startswith(name, "Limit") && u == (uint64_t) -1) ||
763                          (startswith(name, "DefaultLimit") && u == (uint64_t) -1))
764
765                         print_property(name, "%s", "infinity");
766                 else
767                         print_property(name, "%"PRIu64, u);
768
769                 return 1;
770         }
771
772         case SD_BUS_TYPE_INT64: {
773                 int64_t i;
774
775                 r = sd_bus_message_read_basic(m, type, &i);
776                 if (r < 0)
777                         return r;
778
779                 print_property(name, "%"PRIi64, i);
780
781                 return 1;
782         }
783
784         case SD_BUS_TYPE_UINT32: {
785                 uint32_t u;
786
787                 r = sd_bus_message_read_basic(m, type, &u);
788                 if (r < 0)
789                         return r;
790
791                 if (strstr(name, "UMask") || strstr(name, "Mode"))
792                         print_property(name, "%04o", u);
793                 else if (streq(name, "UID")) {
794                         if (u == UID_INVALID)
795                                 print_property(name, "%s", "[not set]");
796                         else
797                                 print_property(name, "%"PRIu32, u);
798                 } else if (streq(name, "GID")) {
799                         if (u == GID_INVALID)
800                                 print_property(name, "%s", "[not set]");
801                         else
802                                 print_property(name, "%"PRIu32, u);
803                 } else
804                         print_property(name, "%"PRIu32, u);
805
806                 return 1;
807         }
808
809         case SD_BUS_TYPE_INT32: {
810                 int32_t i;
811
812                 r = sd_bus_message_read_basic(m, type, &i);
813                 if (r < 0)
814                         return r;
815
816                 print_property(name, "%"PRIi32, i);
817                 return 1;
818         }
819
820         case SD_BUS_TYPE_DOUBLE: {
821                 double d;
822
823                 r = sd_bus_message_read_basic(m, type, &d);
824                 if (r < 0)
825                         return r;
826
827                 print_property(name, "%g", d);
828                 return 1;
829         }
830
831         case SD_BUS_TYPE_ARRAY:
832                 if (streq(contents, "s")) {
833                         bool first = true;
834                         const char *str;
835
836                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, contents);
837                         if (r < 0)
838                                 return r;
839
840                         while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &str)) > 0) {
841                                 bool good;
842
843                                 if (first && !value)
844                                         printf("%s=", name);
845
846                                 /* This property has multiple space-separated values, so
847                                  * neither spaces nor newlines can be allowed in a value. */
848                                 good = str[strcspn(str, " \n")] == '\0';
849
850                                 printf("%s%s", first ? "" : " ", good ? str : "[unprintable]");
851
852                                 first = false;
853                         }
854                         if (r < 0)
855                                 return r;
856
857                         if (first && all && !value)
858                                 printf("%s=", name);
859                         if (!first || all)
860                                 puts("");
861
862                         r = sd_bus_message_exit_container(m);
863                         if (r < 0)
864                                 return r;
865
866                         return 1;
867
868                 } else if (streq(contents, "y")) {
869                         const uint8_t *u;
870                         size_t n;
871
872                         r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, (const void**) &u, &n);
873                         if (r < 0)
874                                 return r;
875
876                         if (all || n > 0) {
877                                 unsigned int i;
878
879                                 if (!value)
880                                         printf("%s=", name);
881
882                                 for (i = 0; i < n; i++)
883                                         printf("%02x", u[i]);
884
885                                 puts("");
886                         }
887
888                         return 1;
889
890                 } else if (streq(contents, "u")) {
891                         uint32_t *u;
892                         size_t n;
893
894                         r = sd_bus_message_read_array(m, SD_BUS_TYPE_UINT32, (const void**) &u, &n);
895                         if (r < 0)
896                                 return r;
897
898                         if (all || n > 0) {
899                                 unsigned int i;
900
901                                 if (!value)
902                                         printf("%s=", name);
903
904                                 for (i = 0; i < n; i++)
905                                         printf("%08x", u[i]);
906
907                                 puts("");
908                         }
909
910                         return 1;
911                 }
912
913                 break;
914         }
915
916         return 0;
917 }
918
919 int bus_message_print_all_properties(
920                 sd_bus_message *m,
921                 bus_message_print_t func,
922                 char **filter,
923                 bool value,
924                 bool all,
925                 Set **found_properties) {
926
927         int r;
928
929         assert(m);
930
931         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
932         if (r < 0)
933                 return r;
934
935         while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
936                 const char *name;
937                 const char *contents;
938
939                 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &name);
940                 if (r < 0)
941                         return r;
942
943                 if (found_properties) {
944                         r = set_ensure_allocated(found_properties, &string_hash_ops);
945                         if (r < 0)
946                                 return log_oom();
947
948                         r = set_put(*found_properties, name);
949                         if (r < 0 && r != EEXIST)
950                                 return log_oom();
951                 }
952
953                 if (!filter || strv_find(filter, name)) {
954                         r = sd_bus_message_peek_type(m, NULL, &contents);
955                         if (r < 0)
956                                 return r;
957
958                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
959                         if (r < 0)
960                                 return r;
961
962                         if (func)
963                                 r = func(name, m, value, all);
964                         if (!func || r == 0)
965                                 r = bus_print_property(name, m, value, all);
966                         if (r < 0)
967                                 return r;
968                         if (r == 0) {
969                                 if (all)
970                                         printf("%s=[unprintable]\n", name);
971                                 /* skip what we didn't read */
972                                 r = sd_bus_message_skip(m, contents);
973                                 if (r < 0)
974                                         return r;
975                         }
976
977                         r = sd_bus_message_exit_container(m);
978                         if (r < 0)
979                                 return r;
980                 } else {
981                         r = sd_bus_message_skip(m, "v");
982                         if (r < 0)
983                                 return r;
984                 }
985
986                 r = sd_bus_message_exit_container(m);
987                 if (r < 0)
988                         return r;
989         }
990         if (r < 0)
991                 return r;
992
993         r = sd_bus_message_exit_container(m);
994         if (r < 0)
995                 return r;
996
997         return 0;
998 }
999
1000 int bus_print_all_properties(
1001                 sd_bus *bus,
1002                 const char *dest,
1003                 const char *path,
1004                 bus_message_print_t func,
1005                 char **filter,
1006                 bool value,
1007                 bool all,
1008                 Set **found_properties) {
1009
1010         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1011         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1012         int r;
1013
1014         assert(bus);
1015         assert(path);
1016
1017         r = sd_bus_call_method(bus,
1018                         dest,
1019                         path,
1020                         "org.freedesktop.DBus.Properties",
1021                         "GetAll",
1022                         &error,
1023                         &reply,
1024                         "s", "");
1025         if (r < 0)
1026                 return r;
1027
1028         return bus_message_print_all_properties(reply, func, filter, value, all, found_properties);
1029 }
1030
1031 int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1032         sd_id128_t *p = userdata;
1033         const void *v;
1034         size_t n;
1035         int r;
1036
1037         r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n);
1038         if (r < 0)
1039                 return r;
1040
1041         if (n == 0)
1042                 *p = SD_ID128_NULL;
1043         else if (n == 16)
1044                 memcpy((*p).bytes, v, n);
1045         else
1046                 return -EINVAL;
1047
1048         return 0;
1049 }
1050
1051 static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, unsigned flags, sd_bus_error *error, void *userdata) {
1052         char type;
1053         int r;
1054
1055         r = sd_bus_message_peek_type(m, &type, NULL);
1056         if (r < 0)
1057                 return r;
1058
1059         switch (type) {
1060
1061         case SD_BUS_TYPE_STRING: {
1062                 const char **p = userdata;
1063                 const char *s;
1064
1065                 r = sd_bus_message_read_basic(m, type, &s);
1066                 if (r < 0)
1067                         return r;
1068
1069                 if (isempty(s))
1070                         s = NULL;
1071
1072                 if (flags & BUS_MAP_STRDUP)
1073                         return free_and_strdup((char **) userdata, s);
1074
1075                 *p = s;
1076                 return 0;
1077         }
1078
1079         case SD_BUS_TYPE_ARRAY: {
1080                 _cleanup_strv_free_ char **l = NULL;
1081                 char ***p = userdata;
1082
1083                 r = bus_message_read_strv_extend(m, &l);
1084                 if (r < 0)
1085                         return r;
1086
1087                 return strv_free_and_replace(*p, l);
1088         }
1089
1090         case SD_BUS_TYPE_BOOLEAN: {
1091                 int b;
1092
1093                 r = sd_bus_message_read_basic(m, type, &b);
1094                 if (r < 0)
1095                         return r;
1096
1097                 if (flags & BUS_MAP_BOOLEAN_AS_BOOL)
1098                         *(bool*) userdata = b;
1099                 else
1100                         *(int*) userdata = b;
1101
1102                 return 0;
1103         }
1104
1105         case SD_BUS_TYPE_INT32:
1106         case SD_BUS_TYPE_UINT32: {
1107                 uint32_t u, *p = userdata;
1108
1109                 r = sd_bus_message_read_basic(m, type, &u);
1110                 if (r < 0)
1111                         return r;
1112
1113                 *p = u;
1114                 return 0;
1115         }
1116
1117         case SD_BUS_TYPE_INT64:
1118         case SD_BUS_TYPE_UINT64: {
1119                 uint64_t t, *p = userdata;
1120
1121                 r = sd_bus_message_read_basic(m, type, &t);
1122                 if (r < 0)
1123                         return r;
1124
1125                 *p = t;
1126                 return 0;
1127         }
1128
1129         case SD_BUS_TYPE_DOUBLE: {
1130                 double d, *p = userdata;
1131
1132                 r = sd_bus_message_read_basic(m, type, &d);
1133                 if (r < 0)
1134                         return r;
1135
1136                 *p = d;
1137                 return 0;
1138         }}
1139
1140         return -EOPNOTSUPP;
1141 }
1142
1143 int bus_message_map_all_properties(
1144                 sd_bus_message *m,
1145                 const struct bus_properties_map *map,
1146                 unsigned flags,
1147                 sd_bus_error *error,
1148                 void *userdata) {
1149
1150         int r;
1151
1152         assert(m);
1153         assert(map);
1154
1155         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
1156         if (r < 0)
1157                 return r;
1158
1159         while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1160                 const struct bus_properties_map *prop;
1161                 const char *member;
1162                 const char *contents;
1163                 void *v;
1164                 unsigned i;
1165
1166                 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
1167                 if (r < 0)
1168                         return r;
1169
1170                 for (i = 0, prop = NULL; map[i].member; i++)
1171                         if (streq(map[i].member, member)) {
1172                                 prop = &map[i];
1173                                 break;
1174                         }
1175
1176                 if (prop) {
1177                         r = sd_bus_message_peek_type(m, NULL, &contents);
1178                         if (r < 0)
1179                                 return r;
1180
1181                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
1182                         if (r < 0)
1183                                 return r;
1184
1185                         v = (uint8_t *)userdata + prop->offset;
1186                         if (map[i].set)
1187                                 r = prop->set(sd_bus_message_get_bus(m), member, m, error, v);
1188                         else
1189                                 r = map_basic(sd_bus_message_get_bus(m), member, m, flags, error, v);
1190                         if (r < 0)
1191                                 return r;
1192
1193                         r = sd_bus_message_exit_container(m);
1194                         if (r < 0)
1195                                 return r;
1196                 } else {
1197                         r = sd_bus_message_skip(m, "v");
1198                         if (r < 0)
1199                                 return r;
1200                 }
1201
1202                 r = sd_bus_message_exit_container(m);
1203                 if (r < 0)
1204                         return r;
1205         }
1206         if (r < 0)
1207                 return r;
1208
1209         return sd_bus_message_exit_container(m);
1210 }
1211
1212 #if 0 /// UNNEEDED by elogind
1213 int bus_message_map_properties_changed(
1214                 sd_bus_message *m,
1215                 const struct bus_properties_map *map,
1216                 unsigned flags,
1217                 sd_bus_error *error,
1218                 void *userdata) {
1219
1220         const char *member;
1221         int r, invalidated, i;
1222
1223         assert(m);
1224         assert(map);
1225
1226         r = bus_message_map_all_properties(m, map, flags, error, userdata);
1227         if (r < 0)
1228                 return r;
1229
1230         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s");
1231         if (r < 0)
1232                 return r;
1233
1234         invalidated = 0;
1235         while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0)
1236                 for (i = 0; map[i].member; i++)
1237                         if (streq(map[i].member, member)) {
1238                                 ++invalidated;
1239                                 break;
1240                         }
1241         if (r < 0)
1242                 return r;
1243
1244         r = sd_bus_message_exit_container(m);
1245         if (r < 0)
1246                 return r;
1247
1248         return invalidated;
1249 }
1250 #endif // 0
1251
1252 int bus_map_all_properties(
1253                 sd_bus *bus,
1254                 const char *destination,
1255                 const char *path,
1256                 const struct bus_properties_map *map,
1257                 unsigned flags,
1258                 sd_bus_error *error,
1259                 sd_bus_message **reply,
1260                 void *userdata) {
1261
1262         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1263         int r;
1264
1265         assert(bus);
1266         assert(destination);
1267         assert(path);
1268         assert(map);
1269         assert(reply || (flags & BUS_MAP_STRDUP));
1270
1271         r = sd_bus_call_method(
1272                         bus,
1273                         destination,
1274                         path,
1275                         "org.freedesktop.DBus.Properties",
1276                         "GetAll",
1277                         error,
1278                         &m,
1279                         "s", "");
1280         if (r < 0)
1281                 return r;
1282
1283         r = bus_message_map_all_properties(m, map, flags, error, userdata);
1284         if (r < 0)
1285                 return r;
1286
1287         if (reply)
1288                 *reply = sd_bus_message_ref(m);
1289
1290         return r;
1291 }
1292
1293 int bus_connect_transport(BusTransport transport, const char *host, bool user, sd_bus **ret) {
1294         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1295         int r;
1296
1297         assert(transport >= 0);
1298         assert(transport < _BUS_TRANSPORT_MAX);
1299         assert(ret);
1300
1301         assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1302         assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1303
1304         switch (transport) {
1305
1306         case BUS_TRANSPORT_LOCAL:
1307 #if 0 /// elogind does not support a user bus
1308                 if (user)
1309                         r = sd_bus_default_user(&bus);
1310 #endif // 0
1311                 else {
1312                         if (sd_booted() <= 0) {
1313                                 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1314                                 log_error("System has not been booted with elogind as init system (PID 1). Can't operate.");
1315
1316                                 return -EHOSTDOWN;
1317                         }
1318                         r = sd_bus_default_system(&bus);
1319                 }
1320                 break;
1321
1322         case BUS_TRANSPORT_REMOTE:
1323                 r = sd_bus_open_system_remote(&bus, host);
1324                 break;
1325
1326         case BUS_TRANSPORT_MACHINE:
1327                 r = sd_bus_open_system_machine(&bus, host);
1328                 break;
1329
1330         default:
1331                 assert_not_reached("Hmm, unknown transport type.");
1332         }
1333         if (r < 0)
1334                 return r;
1335
1336         r = sd_bus_set_exit_on_disconnect(bus, true);
1337         if (r < 0)
1338                 return r;
1339
1340         *ret = TAKE_PTR(bus);
1341
1342         return 0;
1343 }
1344
1345 #if 0 /// UNNEEDED by elogind
1346 int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1347         int r;
1348
1349         assert(transport >= 0);
1350         assert(transport < _BUS_TRANSPORT_MAX);
1351         assert(bus);
1352
1353         assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1354         assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1355
1356         switch (transport) {
1357
1358         case BUS_TRANSPORT_LOCAL:
1359                 if (user)
1360                         r = bus_connect_user_systemd(bus);
1361                 else {
1362                         if (sd_booted() <= 0) {
1363                                 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1364                                 log_error("System has not been booted with systemd as init system (PID 1). Can't operate.");
1365
1366                                 return -EHOSTDOWN;
1367                         }
1368                         r = bus_connect_system_systemd(bus);
1369                 }
1370                 break;
1371
1372         case BUS_TRANSPORT_REMOTE:
1373                 r = sd_bus_open_system_remote(bus, host);
1374                 break;
1375
1376         case BUS_TRANSPORT_MACHINE:
1377                 r = sd_bus_open_system_machine(bus, host);
1378                 break;
1379
1380         default:
1381                 assert_not_reached("Hmm, unknown transport type.");
1382         }
1383
1384         return r;
1385 }
1386 #endif // 0
1387
1388 int bus_property_get_bool(
1389                 sd_bus *bus,
1390                 const char *path,
1391                 const char *interface,
1392                 const char *property,
1393                 sd_bus_message *reply,
1394                 void *userdata,
1395                 sd_bus_error *error) {
1396
1397         int b = *(bool*) userdata;
1398
1399         return sd_bus_message_append_basic(reply, 'b', &b);
1400 }
1401
1402 int bus_property_set_bool(
1403                 sd_bus *bus,
1404                 const char *path,
1405                 const char *interface,
1406                 const char *property,
1407                 sd_bus_message *value,
1408                 void *userdata,
1409                 sd_bus_error *error) {
1410
1411         int b, r;
1412
1413         r = sd_bus_message_read(value, "b", &b);
1414         if (r < 0)
1415                 return r;
1416
1417         *(bool*) userdata = b;
1418         return 0;
1419 }
1420
1421 #if 0 /// UNNEEDED by elogind
1422 int bus_property_get_id128(
1423                 sd_bus *bus,
1424                 const char *path,
1425                 const char *interface,
1426                 const char *property,
1427                 sd_bus_message *reply,
1428                 void *userdata,
1429                 sd_bus_error *error) {
1430
1431         sd_id128_t *id = userdata;
1432
1433         if (sd_id128_is_null(*id)) /* Add an empty array if the ID is zero */
1434                 return sd_bus_message_append(reply, "ay", 0);
1435         else
1436                 return sd_bus_message_append_array(reply, 'y', id->bytes, 16);
1437 }
1438 #endif // 0
1439
1440 #if __SIZEOF_SIZE_T__ != 8
1441 int bus_property_get_size(
1442                 sd_bus *bus,
1443                 const char *path,
1444                 const char *interface,
1445                 const char *property,
1446                 sd_bus_message *reply,
1447                 void *userdata,
1448                 sd_bus_error *error) {
1449
1450         uint64_t sz = *(size_t*) userdata;
1451
1452         return sd_bus_message_append_basic(reply, 't', &sz);
1453 }
1454 #endif
1455
1456 #if __SIZEOF_LONG__ != 8
1457 int bus_property_get_long(
1458                 sd_bus *bus,
1459                 const char *path,
1460                 const char *interface,
1461                 const char *property,
1462                 sd_bus_message *reply,
1463                 void *userdata,
1464                 sd_bus_error *error) {
1465
1466         int64_t l = *(long*) userdata;
1467
1468         return sd_bus_message_append_basic(reply, 'x', &l);
1469 }
1470
1471 int bus_property_get_ulong(
1472                 sd_bus *bus,
1473                 const char *path,
1474                 const char *interface,
1475                 const char *property,
1476                 sd_bus_message *reply,
1477                 void *userdata,
1478                 sd_bus_error *error) {
1479
1480         uint64_t ul = *(unsigned long*) userdata;
1481
1482         return sd_bus_message_append_basic(reply, 't', &ul);
1483 }
1484 #endif
1485
1486 int bus_log_parse_error(int r) {
1487         return log_error_errno(r, "Failed to parse bus message: %m");
1488 }
1489
1490 #if 0 /// UNNEEDED by elogind
1491 int bus_log_create_error(int r) {
1492         return log_error_errno(r, "Failed to create bus message: %m");
1493 }
1494
1495 #endif // 0
1496 #if 0 /// UNNEEDED by elogind
1497 /**
1498  * bus_path_encode_unique() - encode unique object path
1499  * @b: bus connection or NULL
1500  * @prefix: object path prefix
1501  * @sender_id: unique-name of client, or NULL
1502  * @external_id: external ID to be chosen by client, or NULL
1503  * @ret_path: storage for encoded object path pointer
1504  *
1505  * Whenever we provide a bus API that allows clients to create and manage
1506  * server-side objects, we need to provide a unique name for these objects. If
1507  * we let the server choose the name, we suffer from a race condition: If a
1508  * client creates an object asynchronously, it cannot destroy that object until
1509  * it received the method reply. It cannot know the name of the new object,
1510  * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
1511  *
1512  * Therefore, many APIs allow the client to choose the unique name for newly
1513  * created objects. There're two problems to solve, though:
1514  *    1) Object names are usually defined via dbus object paths, which are
1515  *       usually globally namespaced. Therefore, multiple clients must be able
1516  *       to choose unique object names without interference.
1517  *    2) If multiple libraries share the same bus connection, they must be
1518  *       able to choose unique object names without interference.
1519  * The first problem is solved easily by prefixing a name with the
1520  * unique-bus-name of a connection. The server side must enforce this and
1521  * reject any other name. The second problem is solved by providing unique
1522  * suffixes from within sd-bus.
1523  *
1524  * This helper allows clients to create unique object-paths. It uses the
1525  * template '/prefix/sender_id/external_id' and returns the new path in
1526  * @ret_path (must be freed by the caller).
1527  * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
1528  * NULL, this function allocates a unique suffix via @b (by requesting a new
1529  * cookie). If both @sender_id and @external_id are given, @b can be passed as
1530  * NULL.
1531  *
1532  * Returns: 0 on success, negative error code on failure.
1533  */
1534 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
1535         _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
1536         char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
1537         int r;
1538
1539         assert_return(b || (sender_id && external_id), -EINVAL);
1540         assert_return(object_path_is_valid(prefix), -EINVAL);
1541         assert_return(ret_path, -EINVAL);
1542
1543         if (!sender_id) {
1544                 r = sd_bus_get_unique_name(b, &sender_id);
1545                 if (r < 0)
1546                         return r;
1547         }
1548
1549         if (!external_id) {
1550                 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
1551                 external_id = external_buf;
1552         }
1553
1554         sender_label = bus_label_escape(sender_id);
1555         if (!sender_label)
1556                 return -ENOMEM;
1557
1558         external_label = bus_label_escape(external_id);
1559         if (!external_label)
1560                 return -ENOMEM;
1561
1562         p = strjoin(prefix, "/", sender_label, "/", external_label);
1563         if (!p)
1564                 return -ENOMEM;
1565
1566         *ret_path = p;
1567         return 0;
1568 }
1569
1570 /**
1571  * bus_path_decode_unique() - decode unique object path
1572  * @path: object path to decode
1573  * @prefix: object path prefix
1574  * @ret_sender: output parameter for sender-id label
1575  * @ret_external: output parameter for external-id label
1576  *
1577  * This does the reverse of bus_path_encode_unique() (see its description for
1578  * details). Both trailing labels, sender-id and external-id, are unescaped and
1579  * returned in the given output parameters (the caller must free them).
1580  *
1581  * Note that this function returns 0 if the path does not match the template
1582  * (see bus_path_encode_unique()), 1 if it matched.
1583  *
1584  * Returns: Negative error code on failure, 0 if the given object path does not
1585  *          match the template (return parameters are set to NULL), 1 if it was
1586  *          parsed successfully (return parameters contain allocated labels).
1587  */
1588 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
1589         const char *p, *q;
1590         char *sender, *external;
1591
1592         assert(object_path_is_valid(path));
1593         assert(object_path_is_valid(prefix));
1594         assert(ret_sender);
1595         assert(ret_external);
1596
1597         p = object_path_startswith(path, prefix);
1598         if (!p) {
1599                 *ret_sender = NULL;
1600                 *ret_external = NULL;
1601                 return 0;
1602         }
1603
1604         q = strchr(p, '/');
1605         if (!q) {
1606                 *ret_sender = NULL;
1607                 *ret_external = NULL;
1608                 return 0;
1609         }
1610
1611         sender = bus_label_unescape_n(p, q - p);
1612         external = bus_label_unescape(q + 1);
1613         if (!sender || !external) {
1614                 free(sender);
1615                 free(external);
1616                 return -ENOMEM;
1617         }
1618
1619         *ret_sender = sender;
1620         *ret_external = external;
1621         return 1;
1622 }
1623 #endif // 0
1624
1625 #if 0 /// UNNEEDED by elogind
1626 int bus_property_get_rlimit(
1627                 sd_bus *bus,
1628                 const char *path,
1629                 const char *interface,
1630                 const char *property,
1631                 sd_bus_message *reply,
1632                 void *userdata,
1633                 sd_bus_error *error) {
1634
1635         const char *is_soft;
1636         struct rlimit *rl;
1637         uint64_t u;
1638         rlim_t x;
1639
1640         assert(bus);
1641         assert(reply);
1642         assert(userdata);
1643
1644         is_soft = endswith(property, "Soft");
1645
1646         rl = *(struct rlimit**) userdata;
1647         if (rl)
1648                 x = is_soft ? rl->rlim_cur : rl->rlim_max;
1649         else {
1650                 struct rlimit buf = {};
1651                 const char *s, *p;
1652                 int z;
1653
1654                 /* Chop off "Soft" suffix */
1655                 s = is_soft ? strndupa(property, is_soft - property) : property;
1656
1657                 /* Skip over any prefix, such as "Default" */
1658                 assert_se(p = strstr(s, "Limit"));
1659
1660                 z = rlimit_from_string(p + 5);
1661                 assert(z >= 0);
1662
1663                 (void) getrlimit(z, &buf);
1664                 x = is_soft ? buf.rlim_cur : buf.rlim_max;
1665         }
1666
1667         /* rlim_t might have different sizes, let's map RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on all
1668          * archs */
1669         u = x == RLIM_INFINITY ? (uint64_t) -1 : (uint64_t) x;
1670
1671         return sd_bus_message_append(reply, "t", u);
1672 }
1673
1674 int bus_track_add_name_many(sd_bus_track *t, char **l) {
1675         int r = 0;
1676         char **i;
1677
1678         assert(t);
1679
1680         /* Continues adding after failure, and returns the first failure. */
1681
1682         STRV_FOREACH(i, l) {
1683                 int k;
1684
1685                 k = sd_bus_track_add_name(t, *i);
1686                 if (k < 0 && r >= 0)
1687                         r = k;
1688         }
1689
1690         return r;
1691 }
1692 #endif // 0
1693
1694 int bus_open_system_watch_bind_with_description(sd_bus **ret, const char *description) {
1695         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1696         const char *e;
1697         int r;
1698
1699         assert(ret);
1700
1701         /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal turned on. */
1702
1703         r = sd_bus_new(&bus);
1704         if (r < 0)
1705                 return r;
1706
1707         if (description) {
1708                 r = sd_bus_set_description(bus, description);
1709                 if (r < 0)
1710                         return r;
1711         }
1712
1713         e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1714         if (!e)
1715                 e = DEFAULT_SYSTEM_BUS_ADDRESS;
1716
1717         r = sd_bus_set_address(bus, e);
1718         if (r < 0)
1719                 return r;
1720
1721         r = sd_bus_set_bus_client(bus, true);
1722         if (r < 0)
1723                 return r;
1724
1725         r = sd_bus_set_trusted(bus, true);
1726         if (r < 0)
1727                 return r;
1728
1729         r = sd_bus_negotiate_creds(bus, true, SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_EFFECTIVE_CAPS);
1730         if (r < 0)
1731                 return r;
1732
1733         r = sd_bus_set_watch_bind(bus, true);
1734         if (r < 0)
1735                 return r;
1736
1737         r = sd_bus_set_connected_signal(bus, true);
1738         if (r < 0)
1739                 return r;
1740
1741         r = sd_bus_start(bus);
1742         if (r < 0)
1743                 return r;
1744
1745         *ret = TAKE_PTR(bus);
1746
1747         return 0;
1748 }
1749
1750 struct request_name_data {
1751         unsigned n_ref;
1752
1753         const char *name;
1754         uint64_t flags;
1755         void *userdata;
1756 };
1757
1758 static void request_name_destroy_callback(void *userdata) {
1759         struct request_name_data *data = userdata;
1760
1761         assert(data);
1762         assert(data->n_ref > 0);
1763
1764         log_info("%s n_ref=%u", __func__, data->n_ref);
1765
1766         data->n_ref--;
1767         if (data->n_ref == 0)
1768                 free(data);
1769 }
1770
1771 static int reload_dbus_handler(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1772         struct request_name_data *data = userdata;
1773         const sd_bus_error *e;
1774         int r;
1775
1776         assert(data);
1777         assert(data->name);
1778         assert(data->n_ref > 0);
1779
1780         e = sd_bus_message_get_error(m);
1781         if (e) {
1782                 log_error_errno(sd_bus_error_get_errno(e), "Failed to reload DBus configuration: %s", e->message);
1783                 return 1;
1784         }
1785
1786         /* Here, use the default request name handler to avoid an infinite loop of reloading and requesting. */
1787         r = sd_bus_request_name_async(sd_bus_message_get_bus(m), NULL, data->name, data->flags, NULL, data->userdata);
1788         if (r < 0)
1789                 log_error_errno(r, "Failed to request name: %m");
1790
1791         return 1;
1792 }
1793
1794 static int request_name_handler_may_reload_dbus(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1795         struct request_name_data *data = userdata;
1796         uint32_t ret;
1797         int r;
1798
1799         assert(m);
1800         assert(data);
1801
1802         if (sd_bus_message_is_method_error(m, NULL)) {
1803                 const sd_bus_error *e = sd_bus_message_get_error(m);
1804                 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1805
1806                 if (!sd_bus_error_has_name(e, SD_BUS_ERROR_ACCESS_DENIED)) {
1807                         log_debug_errno(sd_bus_error_get_errno(e),
1808                                         "Unable to request name, failing connection: %s",
1809                                         e->message);
1810
1811                         bus_enter_closing(sd_bus_message_get_bus(m));
1812                         return 1;
1813                 }
1814
1815                 log_debug_errno(sd_bus_error_get_errno(e),
1816                                 "Unable to request name, will retry after reloading DBus configuration: %s",
1817                                 e->message);
1818
1819                 /* If systemd-timesyncd.service enables DynamicUser= and dbus.service
1820                  * started before the dynamic user is realized, then the DBus policy
1821                  * about timesyncd has not been enabled yet. So, let's try to reload
1822                  * DBus configuration, and after that request the name again. Note that it
1823                  * seems that no privileges are necessary to call the following method. */
1824
1825                 r = sd_bus_call_method_async(
1826                                 sd_bus_message_get_bus(m),
1827                                 &slot,
1828                                 "org.freedesktop.DBus",
1829                                 "/org/freedesktop/DBus",
1830                                 "org.freedesktop.DBus",
1831                                 "ReloadConfig",
1832                                 reload_dbus_handler,
1833                                 data, NULL);
1834                 if (r < 0) {
1835                         log_error_errno(r, "Failed to reload DBus configuration: %m");
1836                         bus_enter_closing(sd_bus_message_get_bus(m));
1837                         return 1;
1838                 }
1839
1840                 data->n_ref ++;
1841                 assert_se(sd_bus_slot_set_destroy_callback(slot, request_name_destroy_callback) >= 0);
1842
1843                 r = sd_bus_slot_set_floating(slot, true);
1844                 if (r < 0)
1845                         return r;
1846
1847                 return 1;
1848         }
1849
1850         r = sd_bus_message_read(m, "u", &ret);
1851         if (r < 0)
1852                 return r;
1853
1854         switch (ret) {
1855
1856         case BUS_NAME_ALREADY_OWNER:
1857                 log_debug("Already owner of requested service name, ignoring.");
1858                 return 1;
1859
1860         case BUS_NAME_IN_QUEUE:
1861                 log_debug("In queue for requested service name.");
1862                 return 1;
1863
1864         case BUS_NAME_PRIMARY_OWNER:
1865                 log_debug("Successfully acquired requested service name.");
1866                 return 1;
1867
1868         case BUS_NAME_EXISTS:
1869                 log_debug("Requested service name already owned, failing connection.");
1870                 bus_enter_closing(sd_bus_message_get_bus(m));
1871                 return 1;
1872         }
1873
1874         log_debug("Unexpected response from RequestName(), failing connection.");
1875         bus_enter_closing(sd_bus_message_get_bus(m));
1876         return 1;
1877 }
1878
1879 int bus_request_name_async_may_reload_dbus(sd_bus *bus, sd_bus_slot **ret_slot, const char *name, uint64_t flags, void *userdata) {
1880         _cleanup_free_ struct request_name_data *data = NULL;
1881         _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1882         int r;
1883
1884         data = new(struct request_name_data, 1);
1885         if (!data)
1886                 return -ENOMEM;
1887
1888         *data = (struct request_name_data) {
1889                 .n_ref = 1,
1890                 .name = name,
1891                 .flags = flags,
1892                 .userdata = userdata,
1893         };
1894
1895         r = sd_bus_request_name_async(bus, &slot, name, flags, request_name_handler_may_reload_dbus, data);
1896         if (r < 0)
1897                 return r;
1898
1899         assert_se(sd_bus_slot_set_destroy_callback(slot, request_name_destroy_callback) >= 0);
1900         TAKE_PTR(data);
1901
1902         if (ret_slot)
1903                 *ret_slot = TAKE_PTR(slot);
1904         else {
1905                 r = sd_bus_slot_set_floating(slot, true);
1906                 if (r < 0)
1907                         return r;
1908         }
1909
1910         return 0;
1911 }
1912
1913 int bus_reply_pair_array(sd_bus_message *m, char **l) {
1914         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1915         char **k, **v;
1916         int r;
1917
1918         assert(m);
1919
1920         /* Reply to the specified message with a message containing a dictionary put together from the specified
1921          * strv */
1922
1923         r = sd_bus_message_new_method_return(m, &reply);
1924         if (r < 0)
1925                 return r;
1926
1927         r = sd_bus_message_open_container(reply, 'a', "{ss}");
1928         if (r < 0)
1929                 return r;
1930
1931         STRV_FOREACH_PAIR(k, v, l) {
1932                 r = sd_bus_message_append(reply, "{ss}", *k, *v);
1933                 if (r < 0)
1934                         return r;
1935         }
1936
1937         r = sd_bus_message_close_container(reply);
1938         if (r < 0)
1939                 return r;
1940
1941         return sd_bus_send(NULL, reply, NULL);
1942 }