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