chiark / gitweb /
e69b53ea6fa7ee979d513c88f94aae492187edbc
[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") || STR_IN_SET(name, "NextElapseUSecRealtime", "LastTriggerUSec")) {
704                         char timestamp[FORMAT_TIMESTAMP_MAX];
705                         const char *t;
706
707                         t = format_timestamp(timestamp, sizeof(timestamp), u);
708                         if (t || all)
709                                 print_property(name, "%s", strempty(t));
710
711                 } else if (strstr(name, "USec")) {
712                         char timespan[FORMAT_TIMESPAN_MAX];
713
714                         print_property(name, "%s", format_timespan(timespan, sizeof(timespan), u, 0));
715                 } else if (streq(name, "RestrictNamespaces")) {
716                         _cleanup_free_ char *s = NULL;
717                         const char *result;
718
719                         if ((u & NAMESPACE_FLAGS_ALL) == 0)
720                                 result = "yes";
721                         else if ((u & NAMESPACE_FLAGS_ALL) == NAMESPACE_FLAGS_ALL)
722                                 result = "no";
723                         else {
724                                 r = namespace_flags_to_string(u, &s);
725                                 if (r < 0)
726                                         return r;
727
728                                 result = s;
729                         }
730
731                         print_property(name, "%s", result);
732
733                 } else if (streq(name, "MountFlags")) {
734                         const char *result;
735
736                         result = mount_propagation_flags_to_string(u);
737                         if (!result)
738                                 return -EINVAL;
739
740                         print_property(name, "%s", result);
741
742                 } else if (STR_IN_SET(name, "CapabilityBoundingSet", "AmbientCapabilities")) {
743                         _cleanup_free_ char *s = NULL;
744
745                         r = capability_set_to_string_alloc(u, &s);
746                         if (r < 0)
747                                 return r;
748
749                         print_property(name, "%s", s);
750
751                 } else if ((STR_IN_SET(name, "CPUWeight", "StartupCPUWeight", "IOWeight", "StartupIOWeight") && u == CGROUP_WEIGHT_INVALID) ||
752                            (STR_IN_SET(name, "CPUShares", "StartupCPUShares") && u == CGROUP_CPU_SHARES_INVALID) ||
753                            (STR_IN_SET(name, "BlockIOWeight", "StartupBlockIOWeight") && u == CGROUP_BLKIO_WEIGHT_INVALID) ||
754                            (STR_IN_SET(name, "MemoryCurrent", "TasksCurrent") && u == (uint64_t) -1) ||
755                            (endswith(name, "NSec") && u == (uint64_t) -1))
756
757                         print_property(name, "%s", "[not set]");
758
759                 else if ((STR_IN_SET(name, "MemoryLow", "MemoryHigh", "MemoryMax", "MemorySwapMax", "MemoryLimit") && u == CGROUP_LIMIT_MAX) ||
760                          (STR_IN_SET(name, "TasksMax", "DefaultTasksMax") && u == (uint64_t) -1) ||
761                          (startswith(name, "Limit") && u == (uint64_t) -1) ||
762                          (startswith(name, "DefaultLimit") && u == (uint64_t) -1))
763
764                         print_property(name, "%s", "infinity");
765                 else
766                         print_property(name, "%"PRIu64, u);
767
768                 return 1;
769         }
770
771         case SD_BUS_TYPE_INT64: {
772                 int64_t i;
773
774                 r = sd_bus_message_read_basic(m, type, &i);
775                 if (r < 0)
776                         return r;
777
778                 print_property(name, "%"PRIi64, i);
779
780                 return 1;
781         }
782
783         case SD_BUS_TYPE_UINT32: {
784                 uint32_t u;
785
786                 r = sd_bus_message_read_basic(m, type, &u);
787                 if (r < 0)
788                         return r;
789
790                 if (strstr(name, "UMask") || strstr(name, "Mode"))
791                         print_property(name, "%04o", u);
792                 else if (streq(name, "UID")) {
793                         if (u == UID_INVALID)
794                                 print_property(name, "%s", "[not set]");
795                         else
796                                 print_property(name, "%"PRIu32, u);
797                 } else if (streq(name, "GID")) {
798                         if (u == GID_INVALID)
799                                 print_property(name, "%s", "[not set]");
800                         else
801                                 print_property(name, "%"PRIu32, u);
802                 } else
803                         print_property(name, "%"PRIu32, u);
804
805                 return 1;
806         }
807
808         case SD_BUS_TYPE_INT32: {
809                 int32_t i;
810
811                 r = sd_bus_message_read_basic(m, type, &i);
812                 if (r < 0)
813                         return r;
814
815                 print_property(name, "%"PRIi32, i);
816                 return 1;
817         }
818
819         case SD_BUS_TYPE_DOUBLE: {
820                 double d;
821
822                 r = sd_bus_message_read_basic(m, type, &d);
823                 if (r < 0)
824                         return r;
825
826                 print_property(name, "%g", d);
827                 return 1;
828         }
829
830         case SD_BUS_TYPE_ARRAY:
831                 if (streq(contents, "s")) {
832                         bool first = true;
833                         const char *str;
834
835                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, contents);
836                         if (r < 0)
837                                 return r;
838
839                         while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &str)) > 0) {
840                                 bool good;
841
842                                 if (first && !value)
843                                         printf("%s=", name);
844
845                                 /* This property has multiple space-separated values, so
846                                  * neither spaces nor newlines can be allowed in a value. */
847                                 good = str[strcspn(str, " \n")] == '\0';
848
849                                 printf("%s%s", first ? "" : " ", good ? str : "[unprintable]");
850
851                                 first = false;
852                         }
853                         if (r < 0)
854                                 return r;
855
856                         if (first && all && !value)
857                                 printf("%s=", name);
858                         if (!first || all)
859                                 puts("");
860
861                         r = sd_bus_message_exit_container(m);
862                         if (r < 0)
863                                 return r;
864
865                         return 1;
866
867                 } else if (streq(contents, "y")) {
868                         const uint8_t *u;
869                         size_t n;
870
871                         r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, (const void**) &u, &n);
872                         if (r < 0)
873                                 return r;
874
875                         if (all || n > 0) {
876                                 unsigned int i;
877
878                                 if (!value)
879                                         printf("%s=", name);
880
881                                 for (i = 0; i < n; i++)
882                                         printf("%02x", u[i]);
883
884                                 puts("");
885                         }
886
887                         return 1;
888
889                 } else if (streq(contents, "u")) {
890                         uint32_t *u;
891                         size_t n;
892
893                         r = sd_bus_message_read_array(m, SD_BUS_TYPE_UINT32, (const void**) &u, &n);
894                         if (r < 0)
895                                 return r;
896
897                         if (all || n > 0) {
898                                 unsigned int i;
899
900                                 if (!value)
901                                         printf("%s=", name);
902
903                                 for (i = 0; i < n; i++)
904                                         printf("%08x", u[i]);
905
906                                 puts("");
907                         }
908
909                         return 1;
910                 }
911
912                 break;
913         }
914
915         return 0;
916 }
917
918 int bus_message_print_all_properties(
919                 sd_bus_message *m,
920                 bus_message_print_t func,
921                 char **filter,
922                 bool value,
923                 bool all,
924                 Set **found_properties) {
925
926         int r;
927
928         assert(m);
929
930         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
931         if (r < 0)
932                 return r;
933
934         while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
935                 const char *name;
936                 const char *contents;
937
938                 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &name);
939                 if (r < 0)
940                         return r;
941
942                 if (found_properties) {
943                         r = set_ensure_allocated(found_properties, &string_hash_ops);
944                         if (r < 0)
945                                 return log_oom();
946
947                         r = set_put(*found_properties, name);
948                         if (r < 0 && r != EEXIST)
949                                 return log_oom();
950                 }
951
952                 if (!filter || strv_find(filter, name)) {
953                         r = sd_bus_message_peek_type(m, NULL, &contents);
954                         if (r < 0)
955                                 return r;
956
957                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
958                         if (r < 0)
959                                 return r;
960
961                         if (func)
962                                 r = func(name, m, value, all);
963                         if (!func || r == 0)
964                                 r = bus_print_property(name, m, value, all);
965                         if (r < 0)
966                                 return r;
967                         if (r == 0) {
968                                 if (all)
969                                         printf("%s=[unprintable]\n", name);
970                                 /* skip what we didn't read */
971                                 r = sd_bus_message_skip(m, contents);
972                                 if (r < 0)
973                                         return r;
974                         }
975
976                         r = sd_bus_message_exit_container(m);
977                         if (r < 0)
978                                 return r;
979                 } else {
980                         r = sd_bus_message_skip(m, "v");
981                         if (r < 0)
982                                 return r;
983                 }
984
985                 r = sd_bus_message_exit_container(m);
986                 if (r < 0)
987                         return r;
988         }
989         if (r < 0)
990                 return r;
991
992         r = sd_bus_message_exit_container(m);
993         if (r < 0)
994                 return r;
995
996         return 0;
997 }
998
999 int bus_print_all_properties(
1000                 sd_bus *bus,
1001                 const char *dest,
1002                 const char *path,
1003                 bus_message_print_t func,
1004                 char **filter,
1005                 bool value,
1006                 bool all,
1007                 Set **found_properties) {
1008
1009         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1010         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1011         int r;
1012
1013         assert(bus);
1014         assert(path);
1015
1016         r = sd_bus_call_method(bus,
1017                         dest,
1018                         path,
1019                         "org.freedesktop.DBus.Properties",
1020                         "GetAll",
1021                         &error,
1022                         &reply,
1023                         "s", "");
1024         if (r < 0)
1025                 return r;
1026
1027         return bus_message_print_all_properties(reply, func, filter, value, all, found_properties);
1028 }
1029
1030 int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1031         sd_id128_t *p = userdata;
1032         const void *v;
1033         size_t n;
1034         int r;
1035
1036         r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n);
1037         if (r < 0)
1038                 return r;
1039
1040         if (n == 0)
1041                 *p = SD_ID128_NULL;
1042         else if (n == 16)
1043                 memcpy((*p).bytes, v, n);
1044         else
1045                 return -EINVAL;
1046
1047         return 0;
1048 }
1049
1050 static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, unsigned flags, sd_bus_error *error, void *userdata) {
1051         char type;
1052         int r;
1053
1054         r = sd_bus_message_peek_type(m, &type, NULL);
1055         if (r < 0)
1056                 return r;
1057
1058         switch (type) {
1059
1060         case SD_BUS_TYPE_STRING: {
1061                 const char **p = userdata;
1062                 const char *s;
1063
1064                 r = sd_bus_message_read_basic(m, type, &s);
1065                 if (r < 0)
1066                         return r;
1067
1068                 if (isempty(s))
1069                         s = NULL;
1070
1071                 if (flags & BUS_MAP_STRDUP)
1072                         return free_and_strdup((char **) userdata, s);
1073
1074                 *p = s;
1075                 return 0;
1076         }
1077
1078         case SD_BUS_TYPE_ARRAY: {
1079                 _cleanup_strv_free_ char **l = NULL;
1080                 char ***p = userdata;
1081
1082                 r = bus_message_read_strv_extend(m, &l);
1083                 if (r < 0)
1084                         return r;
1085
1086                 return strv_free_and_replace(*p, l);
1087         }
1088
1089         case SD_BUS_TYPE_BOOLEAN: {
1090                 int b;
1091
1092                 r = sd_bus_message_read_basic(m, type, &b);
1093                 if (r < 0)
1094                         return r;
1095
1096                 if (flags & BUS_MAP_BOOLEAN_AS_BOOL)
1097                         *(bool*) userdata = b;
1098                 else
1099                         *(int*) userdata = b;
1100
1101                 return 0;
1102         }
1103
1104         case SD_BUS_TYPE_INT32:
1105         case SD_BUS_TYPE_UINT32: {
1106                 uint32_t u, *p = userdata;
1107
1108                 r = sd_bus_message_read_basic(m, type, &u);
1109                 if (r < 0)
1110                         return r;
1111
1112                 *p = u;
1113                 return 0;
1114         }
1115
1116         case SD_BUS_TYPE_INT64:
1117         case SD_BUS_TYPE_UINT64: {
1118                 uint64_t t, *p = userdata;
1119
1120                 r = sd_bus_message_read_basic(m, type, &t);
1121                 if (r < 0)
1122                         return r;
1123
1124                 *p = t;
1125                 return 0;
1126         }
1127
1128         case SD_BUS_TYPE_DOUBLE: {
1129                 double d, *p = userdata;
1130
1131                 r = sd_bus_message_read_basic(m, type, &d);
1132                 if (r < 0)
1133                         return r;
1134
1135                 *p = d;
1136                 return 0;
1137         }}
1138
1139         return -EOPNOTSUPP;
1140 }
1141
1142 int bus_message_map_all_properties(
1143                 sd_bus_message *m,
1144                 const struct bus_properties_map *map,
1145                 unsigned flags,
1146                 sd_bus_error *error,
1147                 void *userdata) {
1148
1149         int r;
1150
1151         assert(m);
1152         assert(map);
1153
1154         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
1155         if (r < 0)
1156                 return r;
1157
1158         while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1159                 const struct bus_properties_map *prop;
1160                 const char *member;
1161                 const char *contents;
1162                 void *v;
1163                 unsigned i;
1164
1165                 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
1166                 if (r < 0)
1167                         return r;
1168
1169                 for (i = 0, prop = NULL; map[i].member; i++)
1170                         if (streq(map[i].member, member)) {
1171                                 prop = &map[i];
1172                                 break;
1173                         }
1174
1175                 if (prop) {
1176                         r = sd_bus_message_peek_type(m, NULL, &contents);
1177                         if (r < 0)
1178                                 return r;
1179
1180                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
1181                         if (r < 0)
1182                                 return r;
1183
1184                         v = (uint8_t *)userdata + prop->offset;
1185                         if (map[i].set)
1186                                 r = prop->set(sd_bus_message_get_bus(m), member, m, error, v);
1187                         else
1188                                 r = map_basic(sd_bus_message_get_bus(m), member, m, flags, error, v);
1189                         if (r < 0)
1190                                 return r;
1191
1192                         r = sd_bus_message_exit_container(m);
1193                         if (r < 0)
1194                                 return r;
1195                 } else {
1196                         r = sd_bus_message_skip(m, "v");
1197                         if (r < 0)
1198                                 return r;
1199                 }
1200
1201                 r = sd_bus_message_exit_container(m);
1202                 if (r < 0)
1203                         return r;
1204         }
1205         if (r < 0)
1206                 return r;
1207
1208         return sd_bus_message_exit_container(m);
1209 }
1210
1211 #if 0 /// UNNEEDED by elogind
1212 int bus_message_map_properties_changed(
1213                 sd_bus_message *m,
1214                 const struct bus_properties_map *map,
1215                 unsigned flags,
1216                 sd_bus_error *error,
1217                 void *userdata) {
1218
1219         const char *member;
1220         int r, invalidated, i;
1221
1222         assert(m);
1223         assert(map);
1224
1225         r = bus_message_map_all_properties(m, map, flags, error, userdata);
1226         if (r < 0)
1227                 return r;
1228
1229         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s");
1230         if (r < 0)
1231                 return r;
1232
1233         invalidated = 0;
1234         while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0)
1235                 for (i = 0; map[i].member; i++)
1236                         if (streq(map[i].member, member)) {
1237                                 ++invalidated;
1238                                 break;
1239                         }
1240         if (r < 0)
1241                 return r;
1242
1243         r = sd_bus_message_exit_container(m);
1244         if (r < 0)
1245                 return r;
1246
1247         return invalidated;
1248 }
1249 #endif // 0
1250
1251 int bus_map_all_properties(
1252                 sd_bus *bus,
1253                 const char *destination,
1254                 const char *path,
1255                 const struct bus_properties_map *map,
1256                 unsigned flags,
1257                 sd_bus_error *error,
1258                 sd_bus_message **reply,
1259                 void *userdata) {
1260
1261         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1262         int r;
1263
1264         assert(bus);
1265         assert(destination);
1266         assert(path);
1267         assert(map);
1268         assert(reply || (flags & BUS_MAP_STRDUP));
1269
1270         r = sd_bus_call_method(
1271                         bus,
1272                         destination,
1273                         path,
1274                         "org.freedesktop.DBus.Properties",
1275                         "GetAll",
1276                         error,
1277                         &m,
1278                         "s", "");
1279         if (r < 0)
1280                 return r;
1281
1282         r = bus_message_map_all_properties(m, map, flags, error, userdata);
1283         if (r < 0)
1284                 return r;
1285
1286         if (reply)
1287                 *reply = sd_bus_message_ref(m);
1288
1289         return r;
1290 }
1291
1292 int bus_connect_transport(BusTransport transport, const char *host, bool user, sd_bus **ret) {
1293         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1294         int r;
1295
1296         assert(transport >= 0);
1297         assert(transport < _BUS_TRANSPORT_MAX);
1298         assert(ret);
1299
1300         assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1301         assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1302
1303         switch (transport) {
1304
1305         case BUS_TRANSPORT_LOCAL:
1306 #if 0 /// elogind does not support a user bus
1307                 if (user)
1308                         r = sd_bus_default_user(&bus);
1309 #endif // 0
1310                 else {
1311                         if (sd_booted() <= 0) {
1312                                 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1313                                 log_error("System has not been booted with elogind as init system (PID 1). Can't operate.");
1314
1315                                 return -EHOSTDOWN;
1316                         }
1317                         r = sd_bus_default_system(&bus);
1318                 }
1319                 break;
1320
1321         case BUS_TRANSPORT_REMOTE:
1322                 r = sd_bus_open_system_remote(&bus, host);
1323                 break;
1324
1325         case BUS_TRANSPORT_MACHINE:
1326                 r = sd_bus_open_system_machine(&bus, host);
1327                 break;
1328
1329         default:
1330                 assert_not_reached("Hmm, unknown transport type.");
1331         }
1332         if (r < 0)
1333                 return r;
1334
1335         r = sd_bus_set_exit_on_disconnect(bus, true);
1336         if (r < 0)
1337                 return r;
1338
1339         *ret = TAKE_PTR(bus);
1340
1341         return 0;
1342 }
1343
1344 #if 0 /// UNNEEDED by elogind
1345 int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1346         int r;
1347
1348         assert(transport >= 0);
1349         assert(transport < _BUS_TRANSPORT_MAX);
1350         assert(bus);
1351
1352         assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1353         assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1354
1355         switch (transport) {
1356
1357         case BUS_TRANSPORT_LOCAL:
1358                 if (user)
1359                         r = bus_connect_user_systemd(bus);
1360                 else {
1361                         if (sd_booted() <= 0) {
1362                                 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1363                                 log_error("System has not been booted with systemd as init system (PID 1). Can't operate.");
1364
1365                                 return -EHOSTDOWN;
1366                         }
1367                         r = bus_connect_system_systemd(bus);
1368                 }
1369                 break;
1370
1371         case BUS_TRANSPORT_REMOTE:
1372                 r = sd_bus_open_system_remote(bus, host);
1373                 break;
1374
1375         case BUS_TRANSPORT_MACHINE:
1376                 r = sd_bus_open_system_machine(bus, host);
1377                 break;
1378
1379         default:
1380                 assert_not_reached("Hmm, unknown transport type.");
1381         }
1382
1383         return r;
1384 }
1385 #endif // 0
1386
1387 int bus_property_get_bool(
1388                 sd_bus *bus,
1389                 const char *path,
1390                 const char *interface,
1391                 const char *property,
1392                 sd_bus_message *reply,
1393                 void *userdata,
1394                 sd_bus_error *error) {
1395
1396         int b = *(bool*) userdata;
1397
1398         return sd_bus_message_append_basic(reply, 'b', &b);
1399 }
1400
1401 int bus_property_set_bool(
1402                 sd_bus *bus,
1403                 const char *path,
1404                 const char *interface,
1405                 const char *property,
1406                 sd_bus_message *value,
1407                 void *userdata,
1408                 sd_bus_error *error) {
1409
1410         int b, r;
1411
1412         r = sd_bus_message_read(value, "b", &b);
1413         if (r < 0)
1414                 return r;
1415
1416         *(bool*) userdata = b;
1417         return 0;
1418 }
1419
1420 #if 0 /// UNNEEDED by elogind
1421 int bus_property_get_id128(
1422                 sd_bus *bus,
1423                 const char *path,
1424                 const char *interface,
1425                 const char *property,
1426                 sd_bus_message *reply,
1427                 void *userdata,
1428                 sd_bus_error *error) {
1429
1430         sd_id128_t *id = userdata;
1431
1432         if (sd_id128_is_null(*id)) /* Add an empty array if the ID is zero */
1433                 return sd_bus_message_append(reply, "ay", 0);
1434         else
1435                 return sd_bus_message_append_array(reply, 'y', id->bytes, 16);
1436 }
1437 #endif // 0
1438
1439 #if __SIZEOF_SIZE_T__ != 8
1440 int bus_property_get_size(
1441                 sd_bus *bus,
1442                 const char *path,
1443                 const char *interface,
1444                 const char *property,
1445                 sd_bus_message *reply,
1446                 void *userdata,
1447                 sd_bus_error *error) {
1448
1449         uint64_t sz = *(size_t*) userdata;
1450
1451         return sd_bus_message_append_basic(reply, 't', &sz);
1452 }
1453 #endif
1454
1455 #if __SIZEOF_LONG__ != 8
1456 int bus_property_get_long(
1457                 sd_bus *bus,
1458                 const char *path,
1459                 const char *interface,
1460                 const char *property,
1461                 sd_bus_message *reply,
1462                 void *userdata,
1463                 sd_bus_error *error) {
1464
1465         int64_t l = *(long*) userdata;
1466
1467         return sd_bus_message_append_basic(reply, 'x', &l);
1468 }
1469
1470 int bus_property_get_ulong(
1471                 sd_bus *bus,
1472                 const char *path,
1473                 const char *interface,
1474                 const char *property,
1475                 sd_bus_message *reply,
1476                 void *userdata,
1477                 sd_bus_error *error) {
1478
1479         uint64_t ul = *(unsigned long*) userdata;
1480
1481         return sd_bus_message_append_basic(reply, 't', &ul);
1482 }
1483 #endif
1484
1485 int bus_log_parse_error(int r) {
1486         return log_error_errno(r, "Failed to parse bus message: %m");
1487 }
1488
1489 #if 0 /// UNNEEDED by elogind
1490 int bus_log_create_error(int r) {
1491         return log_error_errno(r, "Failed to create bus message: %m");
1492 }
1493
1494 #endif // 0
1495 #if 0 /// UNNEEDED by elogind
1496 /**
1497  * bus_path_encode_unique() - encode unique object path
1498  * @b: bus connection or NULL
1499  * @prefix: object path prefix
1500  * @sender_id: unique-name of client, or NULL
1501  * @external_id: external ID to be chosen by client, or NULL
1502  * @ret_path: storage for encoded object path pointer
1503  *
1504  * Whenever we provide a bus API that allows clients to create and manage
1505  * server-side objects, we need to provide a unique name for these objects. If
1506  * we let the server choose the name, we suffer from a race condition: If a
1507  * client creates an object asynchronously, it cannot destroy that object until
1508  * it received the method reply. It cannot know the name of the new object,
1509  * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
1510  *
1511  * Therefore, many APIs allow the client to choose the unique name for newly
1512  * created objects. There're two problems to solve, though:
1513  *    1) Object names are usually defined via dbus object paths, which are
1514  *       usually globally namespaced. Therefore, multiple clients must be able
1515  *       to choose unique object names without interference.
1516  *    2) If multiple libraries share the same bus connection, they must be
1517  *       able to choose unique object names without interference.
1518  * The first problem is solved easily by prefixing a name with the
1519  * unique-bus-name of a connection. The server side must enforce this and
1520  * reject any other name. The second problem is solved by providing unique
1521  * suffixes from within sd-bus.
1522  *
1523  * This helper allows clients to create unique object-paths. It uses the
1524  * template '/prefix/sender_id/external_id' and returns the new path in
1525  * @ret_path (must be freed by the caller).
1526  * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
1527  * NULL, this function allocates a unique suffix via @b (by requesting a new
1528  * cookie). If both @sender_id and @external_id are given, @b can be passed as
1529  * NULL.
1530  *
1531  * Returns: 0 on success, negative error code on failure.
1532  */
1533 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
1534         _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
1535         char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
1536         int r;
1537
1538         assert_return(b || (sender_id && external_id), -EINVAL);
1539         assert_return(object_path_is_valid(prefix), -EINVAL);
1540         assert_return(ret_path, -EINVAL);
1541
1542         if (!sender_id) {
1543                 r = sd_bus_get_unique_name(b, &sender_id);
1544                 if (r < 0)
1545                         return r;
1546         }
1547
1548         if (!external_id) {
1549                 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
1550                 external_id = external_buf;
1551         }
1552
1553         sender_label = bus_label_escape(sender_id);
1554         if (!sender_label)
1555                 return -ENOMEM;
1556
1557         external_label = bus_label_escape(external_id);
1558         if (!external_label)
1559                 return -ENOMEM;
1560
1561         p = strjoin(prefix, "/", sender_label, "/", external_label);
1562         if (!p)
1563                 return -ENOMEM;
1564
1565         *ret_path = p;
1566         return 0;
1567 }
1568
1569 /**
1570  * bus_path_decode_unique() - decode unique object path
1571  * @path: object path to decode
1572  * @prefix: object path prefix
1573  * @ret_sender: output parameter for sender-id label
1574  * @ret_external: output parameter for external-id label
1575  *
1576  * This does the reverse of bus_path_encode_unique() (see its description for
1577  * details). Both trailing labels, sender-id and external-id, are unescaped and
1578  * returned in the given output parameters (the caller must free them).
1579  *
1580  * Note that this function returns 0 if the path does not match the template
1581  * (see bus_path_encode_unique()), 1 if it matched.
1582  *
1583  * Returns: Negative error code on failure, 0 if the given object path does not
1584  *          match the template (return parameters are set to NULL), 1 if it was
1585  *          parsed successfully (return parameters contain allocated labels).
1586  */
1587 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
1588         const char *p, *q;
1589         char *sender, *external;
1590
1591         assert(object_path_is_valid(path));
1592         assert(object_path_is_valid(prefix));
1593         assert(ret_sender);
1594         assert(ret_external);
1595
1596         p = object_path_startswith(path, prefix);
1597         if (!p) {
1598                 *ret_sender = NULL;
1599                 *ret_external = NULL;
1600                 return 0;
1601         }
1602
1603         q = strchr(p, '/');
1604         if (!q) {
1605                 *ret_sender = NULL;
1606                 *ret_external = NULL;
1607                 return 0;
1608         }
1609
1610         sender = bus_label_unescape_n(p, q - p);
1611         external = bus_label_unescape(q + 1);
1612         if (!sender || !external) {
1613                 free(sender);
1614                 free(external);
1615                 return -ENOMEM;
1616         }
1617
1618         *ret_sender = sender;
1619         *ret_external = external;
1620         return 1;
1621 }
1622 #endif // 0
1623
1624 #if 0 /// UNNEEDED by elogind
1625 int bus_property_get_rlimit(
1626                 sd_bus *bus,
1627                 const char *path,
1628                 const char *interface,
1629                 const char *property,
1630                 sd_bus_message *reply,
1631                 void *userdata,
1632                 sd_bus_error *error) {
1633
1634         const char *is_soft;
1635         struct rlimit *rl;
1636         uint64_t u;
1637         rlim_t x;
1638
1639         assert(bus);
1640         assert(reply);
1641         assert(userdata);
1642
1643         is_soft = endswith(property, "Soft");
1644
1645         rl = *(struct rlimit**) userdata;
1646         if (rl)
1647                 x = is_soft ? rl->rlim_cur : rl->rlim_max;
1648         else {
1649                 struct rlimit buf = {};
1650                 const char *s, *p;
1651                 int z;
1652
1653                 /* Chop off "Soft" suffix */
1654                 s = is_soft ? strndupa(property, is_soft - property) : property;
1655
1656                 /* Skip over any prefix, such as "Default" */
1657                 assert_se(p = strstr(s, "Limit"));
1658
1659                 z = rlimit_from_string(p + 5);
1660                 assert(z >= 0);
1661
1662                 (void) getrlimit(z, &buf);
1663                 x = is_soft ? buf.rlim_cur : buf.rlim_max;
1664         }
1665
1666         /* rlim_t might have different sizes, let's map RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on all
1667          * archs */
1668         u = x == RLIM_INFINITY ? (uint64_t) -1 : (uint64_t) x;
1669
1670         return sd_bus_message_append(reply, "t", u);
1671 }
1672
1673 int bus_track_add_name_many(sd_bus_track *t, char **l) {
1674         int r = 0;
1675         char **i;
1676
1677         assert(t);
1678
1679         /* Continues adding after failure, and returns the first failure. */
1680
1681         STRV_FOREACH(i, l) {
1682                 int k;
1683
1684                 k = sd_bus_track_add_name(t, *i);
1685                 if (k < 0 && r >= 0)
1686                         r = k;
1687         }
1688
1689         return r;
1690 }
1691 #endif // 0
1692
1693 int bus_open_system_watch_bind_with_description(sd_bus **ret, const char *description) {
1694         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1695         const char *e;
1696         int r;
1697
1698         assert(ret);
1699
1700         /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal turned on. */
1701
1702         r = sd_bus_new(&bus);
1703         if (r < 0)
1704                 return r;
1705
1706         if (description) {
1707                 r = sd_bus_set_description(bus, description);
1708                 if (r < 0)
1709                         return r;
1710         }
1711
1712         e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1713         if (!e)
1714                 e = DEFAULT_SYSTEM_BUS_ADDRESS;
1715
1716         r = sd_bus_set_address(bus, e);
1717         if (r < 0)
1718                 return r;
1719
1720         r = sd_bus_set_bus_client(bus, true);
1721         if (r < 0)
1722                 return r;
1723
1724         r = sd_bus_set_trusted(bus, true);
1725         if (r < 0)
1726                 return r;
1727
1728         r = sd_bus_negotiate_creds(bus, true, SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_EFFECTIVE_CAPS);
1729         if (r < 0)
1730                 return r;
1731
1732         r = sd_bus_set_watch_bind(bus, true);
1733         if (r < 0)
1734                 return r;
1735
1736         r = sd_bus_set_connected_signal(bus, true);
1737         if (r < 0)
1738                 return r;
1739
1740         r = sd_bus_start(bus);
1741         if (r < 0)
1742                 return r;
1743
1744         *ret = TAKE_PTR(bus);
1745
1746         return 0;
1747 }
1748
1749 struct request_name_data {
1750         unsigned n_ref;
1751
1752         const char *name;
1753         uint64_t flags;
1754         void *userdata;
1755 };
1756
1757 static void request_name_destroy_callback(void *userdata) {
1758         struct request_name_data *data = userdata;
1759
1760         assert(data);
1761         assert(data->n_ref > 0);
1762
1763         log_info("%s n_ref=%u", __func__, data->n_ref);
1764
1765         data->n_ref--;
1766         if (data->n_ref == 0)
1767                 free(data);
1768 }
1769
1770 static int reload_dbus_handler(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1771         struct request_name_data *data = userdata;
1772         const sd_bus_error *e;
1773         int r;
1774
1775         assert(data);
1776         assert(data->name);
1777         assert(data->n_ref > 0);
1778
1779         e = sd_bus_message_get_error(m);
1780         if (e) {
1781                 log_error_errno(sd_bus_error_get_errno(e), "Failed to reload DBus configuration: %s", e->message);
1782                 return 1;
1783         }
1784
1785         /* Here, use the default request name handler to avoid an infinite loop of reloading and requesting. */
1786         r = sd_bus_request_name_async(sd_bus_message_get_bus(m), NULL, data->name, data->flags, NULL, data->userdata);
1787         if (r < 0)
1788                 log_error_errno(r, "Failed to request name: %m");
1789
1790         return 1;
1791 }
1792
1793 static int request_name_handler_may_reload_dbus(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1794         struct request_name_data *data = userdata;
1795         uint32_t ret;
1796         int r;
1797
1798         assert(m);
1799         assert(data);
1800
1801         if (sd_bus_message_is_method_error(m, NULL)) {
1802                 const sd_bus_error *e = sd_bus_message_get_error(m);
1803                 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1804
1805                 if (!sd_bus_error_has_name(e, SD_BUS_ERROR_ACCESS_DENIED)) {
1806                         log_debug_errno(sd_bus_error_get_errno(e),
1807                                         "Unable to request name, failing connection: %s",
1808                                         e->message);
1809
1810                         bus_enter_closing(sd_bus_message_get_bus(m));
1811                         return 1;
1812                 }
1813
1814                 log_debug_errno(sd_bus_error_get_errno(e),
1815                                 "Unable to request name, will retry after reloading DBus configuration: %s",
1816                                 e->message);
1817
1818                 /* If systemd-timesyncd.service enables DynamicUser= and dbus.service
1819                  * started before the dynamic user is realized, then the DBus policy
1820                  * about timesyncd has not been enabled yet. So, let's try to reload
1821                  * DBus configuration, and after that request the name again. Note that it
1822                  * seems that no privileges are necessary to call the following method. */
1823
1824                 r = sd_bus_call_method_async(
1825                                 sd_bus_message_get_bus(m),
1826                                 &slot,
1827                                 "org.freedesktop.DBus",
1828                                 "/org/freedesktop/DBus",
1829                                 "org.freedesktop.DBus",
1830                                 "ReloadConfig",
1831                                 reload_dbus_handler,
1832                                 data, NULL);
1833                 if (r < 0) {
1834                         log_error_errno(r, "Failed to reload DBus configuration: %m");
1835                         bus_enter_closing(sd_bus_message_get_bus(m));
1836                         return 1;
1837                 }
1838
1839                 data->n_ref ++;
1840                 assert_se(sd_bus_slot_set_destroy_callback(slot, request_name_destroy_callback) >= 0);
1841
1842                 r = sd_bus_slot_set_floating(slot, true);
1843                 if (r < 0)
1844                         return r;
1845
1846                 return 1;
1847         }
1848
1849         r = sd_bus_message_read(m, "u", &ret);
1850         if (r < 0)
1851                 return r;
1852
1853         switch (ret) {
1854
1855         case BUS_NAME_ALREADY_OWNER:
1856                 log_debug("Already owner of requested service name, ignoring.");
1857                 return 1;
1858
1859         case BUS_NAME_IN_QUEUE:
1860                 log_debug("In queue for requested service name.");
1861                 return 1;
1862
1863         case BUS_NAME_PRIMARY_OWNER:
1864                 log_debug("Successfully acquired requested service name.");
1865                 return 1;
1866
1867         case BUS_NAME_EXISTS:
1868                 log_debug("Requested service name already owned, failing connection.");
1869                 bus_enter_closing(sd_bus_message_get_bus(m));
1870                 return 1;
1871         }
1872
1873         log_debug("Unexpected response from RequestName(), failing connection.");
1874         bus_enter_closing(sd_bus_message_get_bus(m));
1875         return 1;
1876 }
1877
1878 int bus_request_name_async_may_reload_dbus(sd_bus *bus, sd_bus_slot **ret_slot, const char *name, uint64_t flags, void *userdata) {
1879         _cleanup_free_ struct request_name_data *data = NULL;
1880         _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1881         int r;
1882
1883         data = new(struct request_name_data, 1);
1884         if (!data)
1885                 return -ENOMEM;
1886
1887         *data = (struct request_name_data) {
1888                 .n_ref = 1,
1889                 .name = name,
1890                 .flags = flags,
1891                 .userdata = userdata,
1892         };
1893
1894         r = sd_bus_request_name_async(bus, &slot, name, flags, request_name_handler_may_reload_dbus, data);
1895         if (r < 0)
1896                 return r;
1897
1898         assert_se(sd_bus_slot_set_destroy_callback(slot, request_name_destroy_callback) >= 0);
1899         TAKE_PTR(data);
1900
1901         if (ret_slot)
1902                 *ret_slot = TAKE_PTR(slot);
1903         else {
1904                 r = sd_bus_slot_set_floating(slot, true);
1905                 if (r < 0)
1906                         return r;
1907         }
1908
1909         return 0;
1910 }
1911
1912 int bus_reply_pair_array(sd_bus_message *m, char **l) {
1913         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1914         char **k, **v;
1915         int r;
1916
1917         assert(m);
1918
1919         /* Reply to the specified message with a message containing a dictionary put together from the specified
1920          * strv */
1921
1922         r = sd_bus_message_new_method_return(m, &reply);
1923         if (r < 0)
1924                 return r;
1925
1926         r = sd_bus_message_open_container(reply, 'a', "{ss}");
1927         if (r < 0)
1928                 return r;
1929
1930         STRV_FOREACH_PAIR(k, v, l) {
1931                 r = sd_bus_message_append(reply, "{ss}", *k, *v);
1932                 if (r < 0)
1933                         return r;
1934         }
1935
1936         r = sd_bus_message_close_container(reply);
1937         if (r < 0)
1938                 return r;
1939
1940         return sd_bus_send(NULL, reply, NULL);
1941 }