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