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