polkit: when authorizing via PK let's re-resolve callback/userdata instead of caching it
[systemd.io.git] / src / shared / bus-util.c
blob58a9203a41948cd5cff8097a3e9eef13f599e513
1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <inttypes.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/ioctl.h>
10 #include <sys/resource.h>
11 #include <sys/socket.h>
12 #include <unistd.h>
14 #include "sd-bus-protocol.h"
15 #include "sd-bus.h"
16 #include "sd-daemon.h"
17 #include "sd-event.h"
18 #include "sd-id128.h"
20 #include "alloc-util.h"
21 #include "bus-internal.h"
22 #include "bus-label.h"
23 #include "bus-message.h"
24 #include "bus-util.h"
25 #include "cap-list.h"
26 #include "cgroup-util.h"
27 #include "def.h"
28 #include "escape.h"
29 #include "fd-util.h"
30 #include "missing.h"
31 #include "mount-util.h"
32 #include "nsflags.h"
33 #include "parse-util.h"
34 #include "proc-cmdline.h"
35 #include "rlimit-util.h"
36 #include "stdio-util.h"
37 #include "strv.h"
38 #include "user-util.h"
40 static int name_owner_change_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
41 sd_event *e = userdata;
43 assert(m);
44 assert(e);
46 sd_bus_close(sd_bus_message_get_bus(m));
47 sd_event_exit(e, 0);
49 return 1;
52 int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name) {
53 const char *match;
54 const char *unique;
55 int r;
57 assert(e);
58 assert(bus);
59 assert(name);
61 /* We unregister the name here and then wait for the
62 * NameOwnerChanged signal for this event to arrive before we
63 * quit. We do this in order to make sure that any queued
64 * requests are still processed before we really exit. */
66 r = sd_bus_get_unique_name(bus, &unique);
67 if (r < 0)
68 return r;
70 match = strjoina(
71 "sender='org.freedesktop.DBus',"
72 "type='signal',"
73 "interface='org.freedesktop.DBus',"
74 "member='NameOwnerChanged',"
75 "path='/org/freedesktop/DBus',"
76 "arg0='", name, "',",
77 "arg1='", unique, "',",
78 "arg2=''");
80 r = sd_bus_add_match_async(bus, NULL, match, name_owner_change_callback, NULL, e);
81 if (r < 0)
82 return r;
84 r = sd_bus_release_name_async(bus, NULL, name, NULL, NULL);
85 if (r < 0)
86 return r;
88 return 0;
91 int bus_event_loop_with_idle(
92 sd_event *e,
93 sd_bus *bus,
94 const char *name,
95 usec_t timeout,
96 check_idle_t check_idle,
97 void *userdata) {
98 bool exiting = false;
99 int r, code;
101 assert(e);
102 assert(bus);
103 assert(name);
105 for (;;) {
106 bool idle;
108 r = sd_event_get_state(e);
109 if (r < 0)
110 return r;
111 if (r == SD_EVENT_FINISHED)
112 break;
114 if (check_idle)
115 idle = check_idle(userdata);
116 else
117 idle = true;
119 r = sd_event_run(e, exiting || !idle ? (uint64_t) -1 : timeout);
120 if (r < 0)
121 return r;
123 if (r == 0 && !exiting && idle) {
125 r = sd_bus_try_close(bus);
126 if (r == -EBUSY)
127 continue;
129 /* Fallback for dbus1 connections: we
130 * unregister the name and wait for the
131 * response to come through for it */
132 if (r == -EOPNOTSUPP) {
134 /* Inform the service manager that we
135 * are going down, so that it will
136 * queue all further start requests,
137 * instead of assuming we are already
138 * running. */
139 sd_notify(false, "STOPPING=1");
141 r = bus_async_unregister_and_exit(e, bus, name);
142 if (r < 0)
143 return r;
145 exiting = true;
146 continue;
149 if (r < 0)
150 return r;
152 sd_event_exit(e, 0);
153 break;
157 r = sd_event_get_exit_code(e, &code);
158 if (r < 0)
159 return r;
161 return code;
164 int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error) {
165 _cleanup_(sd_bus_message_unrefp) sd_bus_message *rep = NULL;
166 int r, has_owner = 0;
168 assert(c);
169 assert(name);
171 r = sd_bus_call_method(c,
172 "org.freedesktop.DBus",
173 "/org/freedesktop/dbus",
174 "org.freedesktop.DBus",
175 "NameHasOwner",
176 error,
177 &rep,
178 "s",
179 name);
180 if (r < 0)
181 return r;
183 r = sd_bus_message_read_basic(rep, 'b', &has_owner);
184 if (r < 0)
185 return sd_bus_error_set_errno(error, r);
187 return has_owner;
190 static int check_good_user(sd_bus_message *m, uid_t good_user) {
191 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
192 uid_t sender_uid;
193 int r;
195 assert(m);
197 if (good_user == UID_INVALID)
198 return 0;
200 r = sd_bus_query_sender_creds(m, SD_BUS_CREDS_EUID, &creds);
201 if (r < 0)
202 return r;
204 /* Don't trust augmented credentials for authorization */
205 assert_return((sd_bus_creds_get_augmented_mask(creds) & SD_BUS_CREDS_EUID) == 0, -EPERM);
207 r = sd_bus_creds_get_euid(creds, &sender_uid);
208 if (r < 0)
209 return r;
211 return sender_uid == good_user;
214 int bus_test_polkit(
215 sd_bus_message *call,
216 int capability,
217 const char *action,
218 const char **details,
219 uid_t good_user,
220 bool *_challenge,
221 sd_bus_error *e) {
223 int r;
225 assert(call);
226 assert(action);
228 /* Tests non-interactively! */
230 r = check_good_user(call, good_user);
231 if (r != 0)
232 return r;
234 r = sd_bus_query_sender_privilege(call, capability);
235 if (r < 0)
236 return r;
237 else if (r > 0)
238 return 1;
239 #if ENABLE_POLKIT
240 else {
241 _cleanup_(sd_bus_message_unrefp) sd_bus_message *request = NULL;
242 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
243 int authorized = false, challenge = false;
244 const char *sender, **k, **v;
246 sender = sd_bus_message_get_sender(call);
247 if (!sender)
248 return -EBADMSG;
250 r = sd_bus_message_new_method_call(
251 call->bus,
252 &request,
253 "org.freedesktop.PolicyKit1",
254 "/org/freedesktop/PolicyKit1/Authority",
255 "org.freedesktop.PolicyKit1.Authority",
256 "CheckAuthorization");
257 if (r < 0)
258 return r;
260 r = sd_bus_message_append(
261 request,
262 "(sa{sv})s",
263 "system-bus-name", 1, "name", "s", sender,
264 action);
265 if (r < 0)
266 return r;
268 r = sd_bus_message_open_container(request, 'a', "{ss}");
269 if (r < 0)
270 return r;
272 STRV_FOREACH_PAIR(k, v, details) {
273 r = sd_bus_message_append(request, "{ss}", *k, *v);
274 if (r < 0)
275 return r;
278 r = sd_bus_message_close_container(request);
279 if (r < 0)
280 return r;
282 r = sd_bus_message_append(request, "us", 0, NULL);
283 if (r < 0)
284 return r;
286 r = sd_bus_call(call->bus, request, 0, e, &reply);
287 if (r < 0) {
288 /* Treat no PK available as access denied */
289 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN)) {
290 sd_bus_error_free(e);
291 return -EACCES;
294 return r;
297 r = sd_bus_message_enter_container(reply, 'r', "bba{ss}");
298 if (r < 0)
299 return r;
301 r = sd_bus_message_read(reply, "bb", &authorized, &challenge);
302 if (r < 0)
303 return r;
305 if (authorized)
306 return 1;
308 if (_challenge) {
309 *_challenge = challenge;
310 return 0;
313 #endif
315 return -EACCES;
318 #if ENABLE_POLKIT
320 typedef struct AsyncPolkitQuery {
321 sd_bus_message *request, *reply;
322 sd_bus_slot *slot;
324 Hashmap *registry;
325 sd_event_source *defer_event_source;
326 } AsyncPolkitQuery;
328 static void async_polkit_query_free(AsyncPolkitQuery *q) {
330 if (!q)
331 return;
333 sd_bus_slot_unref(q->slot);
335 if (q->registry && q->request)
336 hashmap_remove(q->registry, q->request);
338 sd_bus_message_unref(q->request);
339 sd_bus_message_unref(q->reply);
341 sd_event_source_disable_unref(q->defer_event_source);
342 free(q);
345 static int async_polkit_defer(sd_event_source *s, void *userdata) {
346 AsyncPolkitQuery *q = userdata;
348 assert(s);
350 /* This is called as idle event source after we processed the async polkit reply, hopefully after the
351 * method call we re-enqueued has been properly processed. */
353 async_polkit_query_free(q);
354 return 0;
357 static int async_polkit_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
358 _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
359 AsyncPolkitQuery *q = userdata;
360 int r;
362 assert(reply);
363 assert(q);
365 assert(q->slot);
366 q->slot = sd_bus_slot_unref(q->slot);
368 assert(!q->reply);
369 q->reply = sd_bus_message_ref(reply);
371 /* Now, let's dispatch the original message a second time be re-enqueing. This will then traverse the
372 * whole message processing again, and thus re-validating and re-retrieving the "userdata" field
373 * again.
375 * We install an idle event loop event to clean-up the PolicyKit request data when we are idle again,
376 * i.e. after the second time the message is processed is complete. */
378 assert(!q->defer_event_source);
379 r = sd_event_add_defer(sd_bus_get_event(sd_bus_message_get_bus(reply)), &q->defer_event_source, async_polkit_defer, q);
380 if (r < 0)
381 goto fail;
383 r = sd_event_source_set_priority(q->defer_event_source, SD_EVENT_PRIORITY_IDLE);
384 if (r < 0)
385 goto fail;
387 r = sd_event_source_set_enabled(q->defer_event_source, SD_EVENT_ONESHOT);
388 if (r < 0)
389 goto fail;
391 r = sd_bus_message_rewind(q->request, true);
392 if (r < 0)
393 goto fail;
395 r = sd_bus_enqueue_for_read(sd_bus_message_get_bus(q->request), q->request);
396 if (r < 0)
397 goto fail;
399 return 1;
401 fail:
402 log_debug_errno(r, "Processing asynchronous PolicyKit reply failed, ignoring: %m");
403 (void) sd_bus_reply_method_errno(q->request, r, NULL);
404 async_polkit_query_free(q);
406 return r;
409 #endif
411 int bus_verify_polkit_async(
412 sd_bus_message *call,
413 int capability,
414 const char *action,
415 const char **details,
416 bool interactive,
417 uid_t good_user,
418 Hashmap **registry,
419 sd_bus_error *error) {
421 #if ENABLE_POLKIT
422 _cleanup_(sd_bus_message_unrefp) sd_bus_message *pk = NULL;
423 AsyncPolkitQuery *q;
424 int c;
425 #endif
426 const char *sender, **k, **v;
427 int r;
429 assert(call);
430 assert(action);
431 assert(registry);
433 r = check_good_user(call, good_user);
434 if (r != 0)
435 return r;
437 #if ENABLE_POLKIT
438 q = hashmap_get(*registry, call);
439 if (q) {
440 int authorized, challenge;
442 /* This is the second invocation of this function, and
443 * there's already a response from polkit, let's
444 * process it */
445 assert(q->reply);
447 if (sd_bus_message_is_method_error(q->reply, NULL)) {
448 const sd_bus_error *e;
450 /* Copy error from polkit reply */
451 e = sd_bus_message_get_error(q->reply);
452 sd_bus_error_copy(error, e);
454 /* Treat no PK available as access denied */
455 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN))
456 return -EACCES;
458 return -sd_bus_error_get_errno(e);
461 r = sd_bus_message_enter_container(q->reply, 'r', "bba{ss}");
462 if (r >= 0)
463 r = sd_bus_message_read(q->reply, "bb", &authorized, &challenge);
465 if (r < 0)
466 return r;
468 if (authorized)
469 return 1;
471 if (challenge)
472 return sd_bus_error_set(error, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED, "Interactive authentication required.");
474 return -EACCES;
476 #endif
478 r = sd_bus_query_sender_privilege(call, capability);
479 if (r < 0)
480 return r;
481 else if (r > 0)
482 return 1;
484 sender = sd_bus_message_get_sender(call);
485 if (!sender)
486 return -EBADMSG;
488 #if ENABLE_POLKIT
489 c = sd_bus_message_get_allow_interactive_authorization(call);
490 if (c < 0)
491 return c;
492 if (c > 0)
493 interactive = true;
495 r = hashmap_ensure_allocated(registry, NULL);
496 if (r < 0)
497 return r;
499 r = sd_bus_message_new_method_call(
500 call->bus,
501 &pk,
502 "org.freedesktop.PolicyKit1",
503 "/org/freedesktop/PolicyKit1/Authority",
504 "org.freedesktop.PolicyKit1.Authority",
505 "CheckAuthorization");
506 if (r < 0)
507 return r;
509 r = sd_bus_message_append(
511 "(sa{sv})s",
512 "system-bus-name", 1, "name", "s", sender,
513 action);
514 if (r < 0)
515 return r;
517 r = sd_bus_message_open_container(pk, 'a', "{ss}");
518 if (r < 0)
519 return r;
521 STRV_FOREACH_PAIR(k, v, details) {
522 r = sd_bus_message_append(pk, "{ss}", *k, *v);
523 if (r < 0)
524 return r;
527 r = sd_bus_message_close_container(pk);
528 if (r < 0)
529 return r;
531 r = sd_bus_message_append(pk, "us", !!interactive, NULL);
532 if (r < 0)
533 return r;
535 q = new0(AsyncPolkitQuery, 1);
536 if (!q)
537 return -ENOMEM;
539 q->request = sd_bus_message_ref(call);
541 r = hashmap_put(*registry, call, q);
542 if (r < 0) {
543 async_polkit_query_free(q);
544 return r;
547 q->registry = *registry;
549 r = sd_bus_call_async(call->bus, &q->slot, pk, async_polkit_callback, q, 0);
550 if (r < 0) {
551 async_polkit_query_free(q);
552 return r;
555 return 0;
556 #endif
558 return -EACCES;
561 void bus_verify_polkit_async_registry_free(Hashmap *registry) {
562 #if ENABLE_POLKIT
563 hashmap_free_with_destructor(registry, async_polkit_query_free);
564 #endif
567 int bus_check_peercred(sd_bus *c) {
568 struct ucred ucred;
569 int fd, r;
571 assert(c);
573 fd = sd_bus_get_fd(c);
574 if (fd < 0)
575 return fd;
577 r = getpeercred(fd, &ucred);
578 if (r < 0)
579 return r;
581 if (ucred.uid != 0 && ucred.uid != geteuid())
582 return -EPERM;
584 return 1;
587 int bus_connect_system_systemd(sd_bus **_bus) {
588 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
589 int r;
591 assert(_bus);
593 if (geteuid() != 0)
594 return sd_bus_default_system(_bus);
596 /* If we are root then let's talk directly to the system
597 * instance, instead of going via the bus */
599 r = sd_bus_new(&bus);
600 if (r < 0)
601 return r;
603 r = sd_bus_set_address(bus, "unix:path=/run/systemd/private");
604 if (r < 0)
605 return r;
607 r = sd_bus_start(bus);
608 if (r < 0)
609 return sd_bus_default_system(_bus);
611 r = bus_check_peercred(bus);
612 if (r < 0)
613 return r;
615 *_bus = TAKE_PTR(bus);
617 return 0;
620 int bus_connect_user_systemd(sd_bus **_bus) {
621 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
622 _cleanup_free_ char *ee = NULL;
623 const char *e;
624 int r;
626 assert(_bus);
628 e = secure_getenv("XDG_RUNTIME_DIR");
629 if (!e)
630 return sd_bus_default_user(_bus);
632 ee = bus_address_escape(e);
633 if (!ee)
634 return -ENOMEM;
636 r = sd_bus_new(&bus);
637 if (r < 0)
638 return r;
640 bus->address = strjoin("unix:path=", ee, "/systemd/private");
641 if (!bus->address)
642 return -ENOMEM;
644 r = sd_bus_start(bus);
645 if (r < 0)
646 return sd_bus_default_user(_bus);
648 r = bus_check_peercred(bus);
649 if (r < 0)
650 return r;
652 *_bus = TAKE_PTR(bus);
654 return 0;
657 #define print_property(name, fmt, ...) \
658 do { \
659 if (value) \
660 printf(fmt "\n", __VA_ARGS__); \
661 else \
662 printf("%s=" fmt "\n", name, __VA_ARGS__); \
663 } while (0)
665 int bus_print_property(const char *name, sd_bus_message *m, bool value, bool all) {
666 char type;
667 const char *contents;
668 int r;
670 assert(name);
671 assert(m);
673 r = sd_bus_message_peek_type(m, &type, &contents);
674 if (r < 0)
675 return r;
677 switch (type) {
679 case SD_BUS_TYPE_STRING: {
680 const char *s;
682 r = sd_bus_message_read_basic(m, type, &s);
683 if (r < 0)
684 return r;
686 if (all || !isempty(s)) {
687 bool good;
689 /* This property has a single value, so we need to take
690 * care not to print a new line, everything else is OK. */
691 good = !strchr(s, '\n');
692 print_property(name, "%s", good ? s : "[unprintable]");
695 return 1;
698 case SD_BUS_TYPE_BOOLEAN: {
699 int b;
701 r = sd_bus_message_read_basic(m, type, &b);
702 if (r < 0)
703 return r;
705 print_property(name, "%s", yes_no(b));
707 return 1;
710 case SD_BUS_TYPE_UINT64: {
711 uint64_t u;
713 r = sd_bus_message_read_basic(m, type, &u);
714 if (r < 0)
715 return r;
717 /* Yes, heuristics! But we can change this check
718 * should it turn out to not be sufficient */
720 if (endswith(name, "Timestamp") ||
721 STR_IN_SET(name, "NextElapseUSecRealtime", "LastTriggerUSec", "TimeUSec", "RTCTimeUSec")) {
722 char timestamp[FORMAT_TIMESTAMP_MAX];
723 const char *t;
725 t = format_timestamp(timestamp, sizeof(timestamp), u);
726 if (t || all)
727 print_property(name, "%s", strempty(t));
729 } else if (strstr(name, "USec")) {
730 char timespan[FORMAT_TIMESPAN_MAX];
732 print_property(name, "%s", format_timespan(timespan, sizeof(timespan), u, 0));
733 } else if (streq(name, "RestrictNamespaces")) {
734 _cleanup_free_ char *s = NULL;
735 const char *result;
737 if ((u & NAMESPACE_FLAGS_ALL) == 0)
738 result = "yes";
739 else if ((u & NAMESPACE_FLAGS_ALL) == NAMESPACE_FLAGS_ALL)
740 result = "no";
741 else {
742 r = namespace_flags_to_string(u, &s);
743 if (r < 0)
744 return r;
746 result = s;
749 print_property(name, "%s", result);
751 } else if (streq(name, "MountFlags")) {
752 const char *result;
754 result = mount_propagation_flags_to_string(u);
755 if (!result)
756 return -EINVAL;
758 print_property(name, "%s", result);
760 } else if (STR_IN_SET(name, "CapabilityBoundingSet", "AmbientCapabilities")) {
761 _cleanup_free_ char *s = NULL;
763 r = capability_set_to_string_alloc(u, &s);
764 if (r < 0)
765 return r;
767 print_property(name, "%s", s);
769 } else if ((STR_IN_SET(name, "CPUWeight", "StartupCPUWeight", "IOWeight", "StartupIOWeight") && u == CGROUP_WEIGHT_INVALID) ||
770 (STR_IN_SET(name, "CPUShares", "StartupCPUShares") && u == CGROUP_CPU_SHARES_INVALID) ||
771 (STR_IN_SET(name, "BlockIOWeight", "StartupBlockIOWeight") && u == CGROUP_BLKIO_WEIGHT_INVALID) ||
772 (STR_IN_SET(name, "MemoryCurrent", "TasksCurrent") && u == (uint64_t) -1) ||
773 (endswith(name, "NSec") && u == (uint64_t) -1))
775 print_property(name, "%s", "[not set]");
777 else if ((STR_IN_SET(name, "MemoryLow", "MemoryHigh", "MemoryMax", "MemorySwapMax", "MemoryLimit") && u == CGROUP_LIMIT_MAX) ||
778 (STR_IN_SET(name, "TasksMax", "DefaultTasksMax") && u == (uint64_t) -1) ||
779 (startswith(name, "Limit") && u == (uint64_t) -1) ||
780 (startswith(name, "DefaultLimit") && u == (uint64_t) -1))
782 print_property(name, "%s", "infinity");
783 else
784 print_property(name, "%"PRIu64, u);
786 return 1;
789 case SD_BUS_TYPE_INT64: {
790 int64_t i;
792 r = sd_bus_message_read_basic(m, type, &i);
793 if (r < 0)
794 return r;
796 print_property(name, "%"PRIi64, i);
798 return 1;
801 case SD_BUS_TYPE_UINT32: {
802 uint32_t u;
804 r = sd_bus_message_read_basic(m, type, &u);
805 if (r < 0)
806 return r;
808 if (strstr(name, "UMask") || strstr(name, "Mode"))
809 print_property(name, "%04o", u);
810 else if (streq(name, "UID")) {
811 if (u == UID_INVALID)
812 print_property(name, "%s", "[not set]");
813 else
814 print_property(name, "%"PRIu32, u);
815 } else if (streq(name, "GID")) {
816 if (u == GID_INVALID)
817 print_property(name, "%s", "[not set]");
818 else
819 print_property(name, "%"PRIu32, u);
820 } else
821 print_property(name, "%"PRIu32, u);
823 return 1;
826 case SD_BUS_TYPE_INT32: {
827 int32_t i;
829 r = sd_bus_message_read_basic(m, type, &i);
830 if (r < 0)
831 return r;
833 print_property(name, "%"PRIi32, i);
834 return 1;
837 case SD_BUS_TYPE_DOUBLE: {
838 double d;
840 r = sd_bus_message_read_basic(m, type, &d);
841 if (r < 0)
842 return r;
844 print_property(name, "%g", d);
845 return 1;
848 case SD_BUS_TYPE_ARRAY:
849 if (streq(contents, "s")) {
850 bool first = true;
851 const char *str;
853 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, contents);
854 if (r < 0)
855 return r;
857 while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &str)) > 0) {
858 bool good;
860 if (first && !value)
861 printf("%s=", name);
863 /* This property has multiple space-separated values, so
864 * neither spaces nor newlines can be allowed in a value. */
865 good = str[strcspn(str, " \n")] == '\0';
867 printf("%s%s", first ? "" : " ", good ? str : "[unprintable]");
869 first = false;
871 if (r < 0)
872 return r;
874 if (first && all && !value)
875 printf("%s=", name);
876 if (!first || all)
877 puts("");
879 r = sd_bus_message_exit_container(m);
880 if (r < 0)
881 return r;
883 return 1;
885 } else if (streq(contents, "y")) {
886 const uint8_t *u;
887 size_t n;
889 r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, (const void**) &u, &n);
890 if (r < 0)
891 return r;
893 if (all || n > 0) {
894 unsigned int i;
896 if (!value)
897 printf("%s=", name);
899 for (i = 0; i < n; i++)
900 printf("%02x", u[i]);
902 puts("");
905 return 1;
907 } else if (streq(contents, "u")) {
908 uint32_t *u;
909 size_t n;
911 r = sd_bus_message_read_array(m, SD_BUS_TYPE_UINT32, (const void**) &u, &n);
912 if (r < 0)
913 return r;
915 if (all || n > 0) {
916 unsigned int i;
918 if (!value)
919 printf("%s=", name);
921 for (i = 0; i < n; i++)
922 printf("%08x", u[i]);
924 puts("");
927 return 1;
930 break;
933 return 0;
936 int bus_message_print_all_properties(
937 sd_bus_message *m,
938 bus_message_print_t func,
939 char **filter,
940 bool value,
941 bool all,
942 Set **found_properties) {
944 int r;
946 assert(m);
948 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
949 if (r < 0)
950 return r;
952 while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
953 const char *name;
954 const char *contents;
956 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &name);
957 if (r < 0)
958 return r;
960 if (found_properties) {
961 r = set_ensure_allocated(found_properties, &string_hash_ops);
962 if (r < 0)
963 return log_oom();
965 r = set_put(*found_properties, name);
966 if (r < 0 && r != EEXIST)
967 return log_oom();
970 if (!filter || strv_find(filter, name)) {
971 r = sd_bus_message_peek_type(m, NULL, &contents);
972 if (r < 0)
973 return r;
975 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
976 if (r < 0)
977 return r;
979 if (func)
980 r = func(name, m, value, all);
981 if (!func || r == 0)
982 r = bus_print_property(name, m, value, all);
983 if (r < 0)
984 return r;
985 if (r == 0) {
986 if (all)
987 printf("%s=[unprintable]\n", name);
988 /* skip what we didn't read */
989 r = sd_bus_message_skip(m, contents);
990 if (r < 0)
991 return r;
994 r = sd_bus_message_exit_container(m);
995 if (r < 0)
996 return r;
997 } else {
998 r = sd_bus_message_skip(m, "v");
999 if (r < 0)
1000 return r;
1003 r = sd_bus_message_exit_container(m);
1004 if (r < 0)
1005 return r;
1007 if (r < 0)
1008 return r;
1010 r = sd_bus_message_exit_container(m);
1011 if (r < 0)
1012 return r;
1014 return 0;
1017 int bus_print_all_properties(
1018 sd_bus *bus,
1019 const char *dest,
1020 const char *path,
1021 bus_message_print_t func,
1022 char **filter,
1023 bool value,
1024 bool all,
1025 Set **found_properties) {
1027 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1028 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1029 int r;
1031 assert(bus);
1032 assert(path);
1034 r = sd_bus_call_method(bus,
1035 dest,
1036 path,
1037 "org.freedesktop.DBus.Properties",
1038 "GetAll",
1039 &error,
1040 &reply,
1041 "s", "");
1042 if (r < 0)
1043 return r;
1045 return bus_message_print_all_properties(reply, func, filter, value, all, found_properties);
1048 int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1049 sd_id128_t *p = userdata;
1050 const void *v;
1051 size_t n;
1052 int r;
1054 r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n);
1055 if (r < 0)
1056 return r;
1058 if (n == 0)
1059 *p = SD_ID128_NULL;
1060 else if (n == 16)
1061 memcpy((*p).bytes, v, n);
1062 else
1063 return -EINVAL;
1065 return 0;
1068 static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, unsigned flags, sd_bus_error *error, void *userdata) {
1069 char type;
1070 int r;
1072 r = sd_bus_message_peek_type(m, &type, NULL);
1073 if (r < 0)
1074 return r;
1076 switch (type) {
1078 case SD_BUS_TYPE_STRING: {
1079 const char **p = userdata;
1080 const char *s;
1082 r = sd_bus_message_read_basic(m, type, &s);
1083 if (r < 0)
1084 return r;
1086 if (isempty(s))
1087 s = NULL;
1089 if (flags & BUS_MAP_STRDUP)
1090 return free_and_strdup((char **) userdata, s);
1092 *p = s;
1093 return 0;
1096 case SD_BUS_TYPE_ARRAY: {
1097 _cleanup_strv_free_ char **l = NULL;
1098 char ***p = userdata;
1100 r = bus_message_read_strv_extend(m, &l);
1101 if (r < 0)
1102 return r;
1104 return strv_free_and_replace(*p, l);
1107 case SD_BUS_TYPE_BOOLEAN: {
1108 int b;
1110 r = sd_bus_message_read_basic(m, type, &b);
1111 if (r < 0)
1112 return r;
1114 if (flags & BUS_MAP_BOOLEAN_AS_BOOL)
1115 *(bool*) userdata = b;
1116 else
1117 *(int*) userdata = b;
1119 return 0;
1122 case SD_BUS_TYPE_INT32:
1123 case SD_BUS_TYPE_UINT32: {
1124 uint32_t u, *p = userdata;
1126 r = sd_bus_message_read_basic(m, type, &u);
1127 if (r < 0)
1128 return r;
1130 *p = u;
1131 return 0;
1134 case SD_BUS_TYPE_INT64:
1135 case SD_BUS_TYPE_UINT64: {
1136 uint64_t t, *p = userdata;
1138 r = sd_bus_message_read_basic(m, type, &t);
1139 if (r < 0)
1140 return r;
1142 *p = t;
1143 return 0;
1146 case SD_BUS_TYPE_DOUBLE: {
1147 double d, *p = userdata;
1149 r = sd_bus_message_read_basic(m, type, &d);
1150 if (r < 0)
1151 return r;
1153 *p = d;
1154 return 0;
1157 return -EOPNOTSUPP;
1160 int bus_message_map_all_properties(
1161 sd_bus_message *m,
1162 const struct bus_properties_map *map,
1163 unsigned flags,
1164 sd_bus_error *error,
1165 void *userdata) {
1167 int r;
1169 assert(m);
1170 assert(map);
1172 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
1173 if (r < 0)
1174 return r;
1176 while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1177 const struct bus_properties_map *prop;
1178 const char *member;
1179 const char *contents;
1180 void *v;
1181 unsigned i;
1183 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
1184 if (r < 0)
1185 return r;
1187 for (i = 0, prop = NULL; map[i].member; i++)
1188 if (streq(map[i].member, member)) {
1189 prop = &map[i];
1190 break;
1193 if (prop) {
1194 r = sd_bus_message_peek_type(m, NULL, &contents);
1195 if (r < 0)
1196 return r;
1198 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
1199 if (r < 0)
1200 return r;
1202 v = (uint8_t *)userdata + prop->offset;
1203 if (map[i].set)
1204 r = prop->set(sd_bus_message_get_bus(m), member, m, error, v);
1205 else
1206 r = map_basic(sd_bus_message_get_bus(m), member, m, flags, error, v);
1207 if (r < 0)
1208 return r;
1210 r = sd_bus_message_exit_container(m);
1211 if (r < 0)
1212 return r;
1213 } else {
1214 r = sd_bus_message_skip(m, "v");
1215 if (r < 0)
1216 return r;
1219 r = sd_bus_message_exit_container(m);
1220 if (r < 0)
1221 return r;
1223 if (r < 0)
1224 return r;
1226 return sd_bus_message_exit_container(m);
1229 int bus_message_map_properties_changed(
1230 sd_bus_message *m,
1231 const struct bus_properties_map *map,
1232 unsigned flags,
1233 sd_bus_error *error,
1234 void *userdata) {
1236 const char *member;
1237 int r, invalidated, i;
1239 assert(m);
1240 assert(map);
1242 r = bus_message_map_all_properties(m, map, flags, error, userdata);
1243 if (r < 0)
1244 return r;
1246 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s");
1247 if (r < 0)
1248 return r;
1250 invalidated = 0;
1251 while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0)
1252 for (i = 0; map[i].member; i++)
1253 if (streq(map[i].member, member)) {
1254 ++invalidated;
1255 break;
1257 if (r < 0)
1258 return r;
1260 r = sd_bus_message_exit_container(m);
1261 if (r < 0)
1262 return r;
1264 return invalidated;
1267 int bus_map_all_properties(
1268 sd_bus *bus,
1269 const char *destination,
1270 const char *path,
1271 const struct bus_properties_map *map,
1272 unsigned flags,
1273 sd_bus_error *error,
1274 sd_bus_message **reply,
1275 void *userdata) {
1277 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1278 int r;
1280 assert(bus);
1281 assert(destination);
1282 assert(path);
1283 assert(map);
1284 assert(reply || (flags & BUS_MAP_STRDUP));
1286 r = sd_bus_call_method(
1287 bus,
1288 destination,
1289 path,
1290 "org.freedesktop.DBus.Properties",
1291 "GetAll",
1292 error,
1294 "s", "");
1295 if (r < 0)
1296 return r;
1298 r = bus_message_map_all_properties(m, map, flags, error, userdata);
1299 if (r < 0)
1300 return r;
1302 if (reply)
1303 *reply = sd_bus_message_ref(m);
1305 return r;
1308 int bus_connect_transport(BusTransport transport, const char *host, bool user, sd_bus **ret) {
1309 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1310 int r;
1312 assert(transport >= 0);
1313 assert(transport < _BUS_TRANSPORT_MAX);
1314 assert(ret);
1316 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1317 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1319 switch (transport) {
1321 case BUS_TRANSPORT_LOCAL:
1322 if (user)
1323 r = sd_bus_default_user(&bus);
1324 else {
1325 if (sd_booted() <= 0) {
1326 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1327 log_error("System has not been booted with systemd as init system (PID 1). Can't operate.");
1329 return -EHOSTDOWN;
1331 r = sd_bus_default_system(&bus);
1333 break;
1335 case BUS_TRANSPORT_REMOTE:
1336 r = sd_bus_open_system_remote(&bus, host);
1337 break;
1339 case BUS_TRANSPORT_MACHINE:
1340 r = sd_bus_open_system_machine(&bus, host);
1341 break;
1343 default:
1344 assert_not_reached("Hmm, unknown transport type.");
1346 if (r < 0)
1347 return r;
1349 r = sd_bus_set_exit_on_disconnect(bus, true);
1350 if (r < 0)
1351 return r;
1353 *ret = TAKE_PTR(bus);
1355 return 0;
1358 int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1359 int r;
1361 assert(transport >= 0);
1362 assert(transport < _BUS_TRANSPORT_MAX);
1363 assert(bus);
1365 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1366 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1368 switch (transport) {
1370 case BUS_TRANSPORT_LOCAL:
1371 if (user)
1372 r = bus_connect_user_systemd(bus);
1373 else {
1374 if (sd_booted() <= 0) {
1375 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1376 log_error("System has not been booted with systemd as init system (PID 1). Can't operate.");
1378 return -EHOSTDOWN;
1380 r = bus_connect_system_systemd(bus);
1382 break;
1384 case BUS_TRANSPORT_REMOTE:
1385 r = sd_bus_open_system_remote(bus, host);
1386 break;
1388 case BUS_TRANSPORT_MACHINE:
1389 r = sd_bus_open_system_machine(bus, host);
1390 break;
1392 default:
1393 assert_not_reached("Hmm, unknown transport type.");
1396 return r;
1399 int bus_property_get_bool(
1400 sd_bus *bus,
1401 const char *path,
1402 const char *interface,
1403 const char *property,
1404 sd_bus_message *reply,
1405 void *userdata,
1406 sd_bus_error *error) {
1408 int b = *(bool*) userdata;
1410 return sd_bus_message_append_basic(reply, 'b', &b);
1413 int bus_property_set_bool(
1414 sd_bus *bus,
1415 const char *path,
1416 const char *interface,
1417 const char *property,
1418 sd_bus_message *value,
1419 void *userdata,
1420 sd_bus_error *error) {
1422 int b, r;
1424 r = sd_bus_message_read(value, "b", &b);
1425 if (r < 0)
1426 return r;
1428 *(bool*) userdata = b;
1429 return 0;
1432 int bus_property_get_id128(
1433 sd_bus *bus,
1434 const char *path,
1435 const char *interface,
1436 const char *property,
1437 sd_bus_message *reply,
1438 void *userdata,
1439 sd_bus_error *error) {
1441 sd_id128_t *id = userdata;
1443 if (sd_id128_is_null(*id)) /* Add an empty array if the ID is zero */
1444 return sd_bus_message_append(reply, "ay", 0);
1445 else
1446 return sd_bus_message_append_array(reply, 'y', id->bytes, 16);
1449 #if __SIZEOF_SIZE_T__ != 8
1450 int bus_property_get_size(
1451 sd_bus *bus,
1452 const char *path,
1453 const char *interface,
1454 const char *property,
1455 sd_bus_message *reply,
1456 void *userdata,
1457 sd_bus_error *error) {
1459 uint64_t sz = *(size_t*) userdata;
1461 return sd_bus_message_append_basic(reply, 't', &sz);
1463 #endif
1465 #if __SIZEOF_LONG__ != 8
1466 int bus_property_get_long(
1467 sd_bus *bus,
1468 const char *path,
1469 const char *interface,
1470 const char *property,
1471 sd_bus_message *reply,
1472 void *userdata,
1473 sd_bus_error *error) {
1475 int64_t l = *(long*) userdata;
1477 return sd_bus_message_append_basic(reply, 'x', &l);
1480 int bus_property_get_ulong(
1481 sd_bus *bus,
1482 const char *path,
1483 const char *interface,
1484 const char *property,
1485 sd_bus_message *reply,
1486 void *userdata,
1487 sd_bus_error *error) {
1489 uint64_t ul = *(unsigned long*) userdata;
1491 return sd_bus_message_append_basic(reply, 't', &ul);
1493 #endif
1495 int bus_log_parse_error(int r) {
1496 return log_error_errno(r, "Failed to parse bus message: %m");
1499 int bus_log_create_error(int r) {
1500 return log_error_errno(r, "Failed to create bus message: %m");
1504 * bus_path_encode_unique() - encode unique object path
1505 * @b: bus connection or NULL
1506 * @prefix: object path prefix
1507 * @sender_id: unique-name of client, or NULL
1508 * @external_id: external ID to be chosen by client, or NULL
1509 * @ret_path: storage for encoded object path pointer
1511 * Whenever we provide a bus API that allows clients to create and manage
1512 * server-side objects, we need to provide a unique name for these objects. If
1513 * we let the server choose the name, we suffer from a race condition: If a
1514 * client creates an object asynchronously, it cannot destroy that object until
1515 * it received the method reply. It cannot know the name of the new object,
1516 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
1518 * Therefore, many APIs allow the client to choose the unique name for newly
1519 * created objects. There're two problems to solve, though:
1520 * 1) Object names are usually defined via dbus object paths, which are
1521 * usually globally namespaced. Therefore, multiple clients must be able
1522 * to choose unique object names without interference.
1523 * 2) If multiple libraries share the same bus connection, they must be
1524 * able to choose unique object names without interference.
1525 * The first problem is solved easily by prefixing a name with the
1526 * unique-bus-name of a connection. The server side must enforce this and
1527 * reject any other name. The second problem is solved by providing unique
1528 * suffixes from within sd-bus.
1530 * This helper allows clients to create unique object-paths. It uses the
1531 * template '/prefix/sender_id/external_id' and returns the new path in
1532 * @ret_path (must be freed by the caller).
1533 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
1534 * NULL, this function allocates a unique suffix via @b (by requesting a new
1535 * cookie). If both @sender_id and @external_id are given, @b can be passed as
1536 * NULL.
1538 * Returns: 0 on success, negative error code on failure.
1540 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
1541 _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
1542 char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
1543 int r;
1545 assert_return(b || (sender_id && external_id), -EINVAL);
1546 assert_return(object_path_is_valid(prefix), -EINVAL);
1547 assert_return(ret_path, -EINVAL);
1549 if (!sender_id) {
1550 r = sd_bus_get_unique_name(b, &sender_id);
1551 if (r < 0)
1552 return r;
1555 if (!external_id) {
1556 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
1557 external_id = external_buf;
1560 sender_label = bus_label_escape(sender_id);
1561 if (!sender_label)
1562 return -ENOMEM;
1564 external_label = bus_label_escape(external_id);
1565 if (!external_label)
1566 return -ENOMEM;
1568 p = strjoin(prefix, "/", sender_label, "/", external_label);
1569 if (!p)
1570 return -ENOMEM;
1572 *ret_path = p;
1573 return 0;
1577 * bus_path_decode_unique() - decode unique object path
1578 * @path: object path to decode
1579 * @prefix: object path prefix
1580 * @ret_sender: output parameter for sender-id label
1581 * @ret_external: output parameter for external-id label
1583 * This does the reverse of bus_path_encode_unique() (see its description for
1584 * details). Both trailing labels, sender-id and external-id, are unescaped and
1585 * returned in the given output parameters (the caller must free them).
1587 * Note that this function returns 0 if the path does not match the template
1588 * (see bus_path_encode_unique()), 1 if it matched.
1590 * Returns: Negative error code on failure, 0 if the given object path does not
1591 * match the template (return parameters are set to NULL), 1 if it was
1592 * parsed successfully (return parameters contain allocated labels).
1594 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
1595 const char *p, *q;
1596 char *sender, *external;
1598 assert(object_path_is_valid(path));
1599 assert(object_path_is_valid(prefix));
1600 assert(ret_sender);
1601 assert(ret_external);
1603 p = object_path_startswith(path, prefix);
1604 if (!p) {
1605 *ret_sender = NULL;
1606 *ret_external = NULL;
1607 return 0;
1610 q = strchr(p, '/');
1611 if (!q) {
1612 *ret_sender = NULL;
1613 *ret_external = NULL;
1614 return 0;
1617 sender = bus_label_unescape_n(p, q - p);
1618 external = bus_label_unescape(q + 1);
1619 if (!sender || !external) {
1620 free(sender);
1621 free(external);
1622 return -ENOMEM;
1625 *ret_sender = sender;
1626 *ret_external = external;
1627 return 1;
1630 int bus_property_get_rlimit(
1631 sd_bus *bus,
1632 const char *path,
1633 const char *interface,
1634 const char *property,
1635 sd_bus_message *reply,
1636 void *userdata,
1637 sd_bus_error *error) {
1639 const char *is_soft;
1640 struct rlimit *rl;
1641 uint64_t u;
1642 rlim_t x;
1644 assert(bus);
1645 assert(reply);
1646 assert(userdata);
1648 is_soft = endswith(property, "Soft");
1650 rl = *(struct rlimit**) userdata;
1651 if (rl)
1652 x = is_soft ? rl->rlim_cur : rl->rlim_max;
1653 else {
1654 struct rlimit buf = {};
1655 const char *s, *p;
1656 int z;
1658 /* Chop off "Soft" suffix */
1659 s = is_soft ? strndupa(property, is_soft - property) : property;
1661 /* Skip over any prefix, such as "Default" */
1662 assert_se(p = strstr(s, "Limit"));
1664 z = rlimit_from_string(p + 5);
1665 assert(z >= 0);
1667 (void) getrlimit(z, &buf);
1668 x = is_soft ? buf.rlim_cur : buf.rlim_max;
1671 /* rlim_t might have different sizes, let's map RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on all
1672 * archs */
1673 u = x == RLIM_INFINITY ? (uint64_t) -1 : (uint64_t) x;
1675 return sd_bus_message_append(reply, "t", u);
1678 int bus_track_add_name_many(sd_bus_track *t, char **l) {
1679 int r = 0;
1680 char **i;
1682 assert(t);
1684 /* Continues adding after failure, and returns the first failure. */
1686 STRV_FOREACH(i, l) {
1687 int k;
1689 k = sd_bus_track_add_name(t, *i);
1690 if (k < 0 && r >= 0)
1691 r = k;
1694 return r;
1697 int bus_open_system_watch_bind_with_description(sd_bus **ret, const char *description) {
1698 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1699 const char *e;
1700 int r;
1702 assert(ret);
1704 /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal turned on. */
1706 r = sd_bus_new(&bus);
1707 if (r < 0)
1708 return r;
1710 if (description) {
1711 r = sd_bus_set_description(bus, description);
1712 if (r < 0)
1713 return r;
1716 e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1717 if (!e)
1718 e = DEFAULT_SYSTEM_BUS_ADDRESS;
1720 r = sd_bus_set_address(bus, e);
1721 if (r < 0)
1722 return r;
1724 r = sd_bus_set_bus_client(bus, true);
1725 if (r < 0)
1726 return r;
1728 r = sd_bus_set_trusted(bus, true);
1729 if (r < 0)
1730 return r;
1732 r = sd_bus_negotiate_creds(bus, true, SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_EFFECTIVE_CAPS);
1733 if (r < 0)
1734 return r;
1736 r = sd_bus_set_watch_bind(bus, true);
1737 if (r < 0)
1738 return r;
1740 r = sd_bus_set_connected_signal(bus, true);
1741 if (r < 0)
1742 return r;
1744 r = sd_bus_start(bus);
1745 if (r < 0)
1746 return r;
1748 *ret = TAKE_PTR(bus);
1750 return 0;
1753 struct request_name_data {
1754 unsigned n_ref;
1756 const char *name;
1757 uint64_t flags;
1758 void *userdata;
1761 static void request_name_destroy_callback(void *userdata) {
1762 struct request_name_data *data = userdata;
1764 assert(data);
1765 assert(data->n_ref > 0);
1767 log_info("%s n_ref=%u", __func__, data->n_ref);
1769 data->n_ref--;
1770 if (data->n_ref == 0)
1771 free(data);
1774 static int reload_dbus_handler(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1775 struct request_name_data *data = userdata;
1776 const sd_bus_error *e;
1777 int r;
1779 assert(data);
1780 assert(data->name);
1781 assert(data->n_ref > 0);
1783 e = sd_bus_message_get_error(m);
1784 if (e) {
1785 log_error_errno(sd_bus_error_get_errno(e), "Failed to reload DBus configuration: %s", e->message);
1786 return 1;
1789 /* Here, use the default request name handler to avoid an infinite loop of reloading and requesting. */
1790 r = sd_bus_request_name_async(sd_bus_message_get_bus(m), NULL, data->name, data->flags, NULL, data->userdata);
1791 if (r < 0)
1792 log_error_errno(r, "Failed to request name: %m");
1794 return 1;
1797 static int request_name_handler_may_reload_dbus(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1798 struct request_name_data *data = userdata;
1799 uint32_t ret;
1800 int r;
1802 assert(m);
1803 assert(data);
1805 if (sd_bus_message_is_method_error(m, NULL)) {
1806 const sd_bus_error *e = sd_bus_message_get_error(m);
1807 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1809 if (!sd_bus_error_has_name(e, SD_BUS_ERROR_ACCESS_DENIED)) {
1810 log_debug_errno(sd_bus_error_get_errno(e),
1811 "Unable to request name, failing connection: %s",
1812 e->message);
1814 bus_enter_closing(sd_bus_message_get_bus(m));
1815 return 1;
1818 log_debug_errno(sd_bus_error_get_errno(e),
1819 "Unable to request name, will retry after reloading DBus configuration: %s",
1820 e->message);
1822 /* If systemd-timesyncd.service enables DynamicUser= and dbus.service
1823 * started before the dynamic user is realized, then the DBus policy
1824 * about timesyncd has not been enabled yet. So, let's try to reload
1825 * DBus configuration, and after that request the name again. Note that it
1826 * seems that no privileges are necessary to call the following method. */
1828 r = sd_bus_call_method_async(
1829 sd_bus_message_get_bus(m),
1830 &slot,
1831 "org.freedesktop.DBus",
1832 "/org/freedesktop/DBus",
1833 "org.freedesktop.DBus",
1834 "ReloadConfig",
1835 reload_dbus_handler,
1836 data, NULL);
1837 if (r < 0) {
1838 log_error_errno(r, "Failed to reload DBus configuration: %m");
1839 bus_enter_closing(sd_bus_message_get_bus(m));
1840 return 1;
1843 data->n_ref ++;
1844 assert_se(sd_bus_slot_set_destroy_callback(slot, request_name_destroy_callback) >= 0);
1846 r = sd_bus_slot_set_floating(slot, true);
1847 if (r < 0)
1848 return r;
1850 return 1;
1853 r = sd_bus_message_read(m, "u", &ret);
1854 if (r < 0)
1855 return r;
1857 switch (ret) {
1859 case BUS_NAME_ALREADY_OWNER:
1860 log_debug("Already owner of requested service name, ignoring.");
1861 return 1;
1863 case BUS_NAME_IN_QUEUE:
1864 log_debug("In queue for requested service name.");
1865 return 1;
1867 case BUS_NAME_PRIMARY_OWNER:
1868 log_debug("Successfully acquired requested service name.");
1869 return 1;
1871 case BUS_NAME_EXISTS:
1872 log_debug("Requested service name already owned, failing connection.");
1873 bus_enter_closing(sd_bus_message_get_bus(m));
1874 return 1;
1877 log_debug("Unexpected response from RequestName(), failing connection.");
1878 bus_enter_closing(sd_bus_message_get_bus(m));
1879 return 1;
1882 int bus_request_name_async_may_reload_dbus(sd_bus *bus, sd_bus_slot **ret_slot, const char *name, uint64_t flags, void *userdata) {
1883 _cleanup_free_ struct request_name_data *data = NULL;
1884 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1885 int r;
1887 data = new(struct request_name_data, 1);
1888 if (!data)
1889 return -ENOMEM;
1891 *data = (struct request_name_data) {
1892 .n_ref = 1,
1893 .name = name,
1894 .flags = flags,
1895 .userdata = userdata,
1898 r = sd_bus_request_name_async(bus, &slot, name, flags, request_name_handler_may_reload_dbus, data);
1899 if (r < 0)
1900 return r;
1902 assert_se(sd_bus_slot_set_destroy_callback(slot, request_name_destroy_callback) >= 0);
1903 TAKE_PTR(data);
1905 if (ret_slot)
1906 *ret_slot = TAKE_PTR(slot);
1907 else {
1908 r = sd_bus_slot_set_floating(slot, true);
1909 if (r < 0)
1910 return r;
1913 return 0;
1916 int bus_reply_pair_array(sd_bus_message *m, char **l) {
1917 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1918 char **k, **v;
1919 int r;
1921 assert(m);
1923 /* Reply to the specified message with a message containing a dictionary put together from the specified
1924 * strv */
1926 r = sd_bus_message_new_method_return(m, &reply);
1927 if (r < 0)
1928 return r;
1930 r = sd_bus_message_open_container(reply, 'a', "{ss}");
1931 if (r < 0)
1932 return r;
1934 STRV_FOREACH_PAIR(k, v, l) {
1935 r = sd_bus_message_append(reply, "{ss}", *k, *v);
1936 if (r < 0)
1937 return r;
1940 r = sd_bus_message_close_container(reply);
1941 if (r < 0)
1942 return r;
1944 return sd_bus_send(NULL, reply, NULL);