1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/resource.h>
11 #include <sys/socket.h>
14 #include "sd-bus-protocol.h"
16 #include "sd-daemon.h"
20 #include "alloc-util.h"
21 #include "bus-internal.h"
22 #include "bus-label.h"
23 #include "bus-message.h"
26 #include "cgroup-util.h"
31 #include "mount-util.h"
33 #include "parse-util.h"
34 #include "proc-cmdline.h"
35 #include "rlimit-util.h"
36 #include "stdio-util.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
;
46 sd_bus_close(sd_bus_message_get_bus(m
));
52 int bus_async_unregister_and_exit(sd_event
*e
, sd_bus
*bus
, const char *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
);
71 "sender='org.freedesktop.DBus',"
73 "interface='org.freedesktop.DBus',"
74 "member='NameOwnerChanged',"
75 "path='/org/freedesktop/DBus',"
77 "arg1='", unique
, "',",
80 r
= sd_bus_add_match_async(bus
, NULL
, match
, name_owner_change_callback
, NULL
, e
);
84 r
= sd_bus_release_name_async(bus
, NULL
, name
, NULL
, NULL
);
91 int bus_event_loop_with_idle(
96 check_idle_t check_idle
,
108 r
= sd_event_get_state(e
);
111 if (r
== SD_EVENT_FINISHED
)
115 idle
= check_idle(userdata
);
119 r
= sd_event_run(e
, exiting
|| !idle
? (uint64_t) -1 : timeout
);
123 if (r
== 0 && !exiting
&& idle
) {
125 r
= sd_bus_try_close(bus
);
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
139 sd_notify(false, "STOPPING=1");
141 r
= bus_async_unregister_and_exit(e
, bus
, name
);
157 r
= sd_event_get_exit_code(e
, &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;
171 r
= sd_bus_call_method(c
,
172 "org.freedesktop.DBus",
173 "/org/freedesktop/dbus",
174 "org.freedesktop.DBus",
183 r
= sd_bus_message_read_basic(rep
, 'b', &has_owner
);
185 return sd_bus_error_set_errno(error
, r
);
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
;
197 if (good_user
== UID_INVALID
)
200 r
= sd_bus_query_sender_creds(m
, SD_BUS_CREDS_EUID
, &creds
);
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
);
211 return sender_uid
== good_user
;
215 sd_bus_message
*call
,
218 const char **details
,
228 /* Tests non-interactively! */
230 r
= check_good_user(call
, good_user
);
234 r
= sd_bus_query_sender_privilege(call
, capability
);
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
);
250 r
= sd_bus_message_new_method_call(
253 "org.freedesktop.PolicyKit1",
254 "/org/freedesktop/PolicyKit1/Authority",
255 "org.freedesktop.PolicyKit1.Authority",
256 "CheckAuthorization");
260 r
= sd_bus_message_append(
263 "system-bus-name", 1, "name", "s", sender
,
268 r
= sd_bus_message_open_container(request
, 'a', "{ss}");
272 STRV_FOREACH_PAIR(k
, v
, details
) {
273 r
= sd_bus_message_append(request
, "{ss}", *k
, *v
);
278 r
= sd_bus_message_close_container(request
);
282 r
= sd_bus_message_append(request
, "us", 0, NULL
);
286 r
= sd_bus_call(call
->bus
, request
, 0, e
, &reply
);
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
);
297 r
= sd_bus_message_enter_container(reply
, 'r', "bba{ss}");
301 r
= sd_bus_message_read(reply
, "bb", &authorized
, &challenge
);
309 *_challenge
= challenge
;
320 typedef struct AsyncPolkitQuery
{
321 sd_bus_message
*request
, *reply
;
325 sd_event_source
*defer_event_source
;
328 static void async_polkit_query_free(AsyncPolkitQuery
*q
) {
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
);
345 static int async_polkit_defer(sd_event_source
*s
, void *userdata
) {
346 AsyncPolkitQuery
*q
= userdata
;
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
);
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
;
366 q
->slot
= sd_bus_slot_unref(q
->slot
);
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
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
);
383 r
= sd_event_source_set_priority(q
->defer_event_source
, SD_EVENT_PRIORITY_IDLE
);
387 r
= sd_event_source_set_enabled(q
->defer_event_source
, SD_EVENT_ONESHOT
);
391 r
= sd_bus_message_rewind(q
->request
, true);
395 r
= sd_bus_enqueue_for_read(sd_bus_message_get_bus(q
->request
), q
->request
);
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
);
411 int bus_verify_polkit_async(
412 sd_bus_message
*call
,
415 const char **details
,
419 sd_bus_error
*error
) {
422 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*pk
= NULL
;
426 const char *sender
, **k
, **v
;
433 r
= check_good_user(call
, good_user
);
438 q
= hashmap_get(*registry
, call
);
440 int authorized
, challenge
;
442 /* This is the second invocation of this function, and
443 * there's already a response from polkit, let's
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
))
458 return -sd_bus_error_get_errno(e
);
461 r
= sd_bus_message_enter_container(q
->reply
, 'r', "bba{ss}");
463 r
= sd_bus_message_read(q
->reply
, "bb", &authorized
, &challenge
);
472 return sd_bus_error_set(error
, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED
, "Interactive authentication required.");
478 r
= sd_bus_query_sender_privilege(call
, capability
);
484 sender
= sd_bus_message_get_sender(call
);
489 c
= sd_bus_message_get_allow_interactive_authorization(call
);
495 r
= hashmap_ensure_allocated(registry
, NULL
);
499 r
= sd_bus_message_new_method_call(
502 "org.freedesktop.PolicyKit1",
503 "/org/freedesktop/PolicyKit1/Authority",
504 "org.freedesktop.PolicyKit1.Authority",
505 "CheckAuthorization");
509 r
= sd_bus_message_append(
512 "system-bus-name", 1, "name", "s", sender
,
517 r
= sd_bus_message_open_container(pk
, 'a', "{ss}");
521 STRV_FOREACH_PAIR(k
, v
, details
) {
522 r
= sd_bus_message_append(pk
, "{ss}", *k
, *v
);
527 r
= sd_bus_message_close_container(pk
);
531 r
= sd_bus_message_append(pk
, "us", !!interactive
, NULL
);
535 q
= new0(AsyncPolkitQuery
, 1);
539 q
->request
= sd_bus_message_ref(call
);
541 r
= hashmap_put(*registry
, call
, q
);
543 async_polkit_query_free(q
);
547 q
->registry
= *registry
;
549 r
= sd_bus_call_async(call
->bus
, &q
->slot
, pk
, async_polkit_callback
, q
, 0);
551 async_polkit_query_free(q
);
561 void bus_verify_polkit_async_registry_free(Hashmap
*registry
) {
563 hashmap_free_with_destructor(registry
, async_polkit_query_free
);
567 int bus_check_peercred(sd_bus
*c
) {
573 fd
= sd_bus_get_fd(c
);
577 r
= getpeercred(fd
, &ucred
);
581 if (ucred
.uid
!= 0 && ucred
.uid
!= geteuid())
587 int bus_connect_system_systemd(sd_bus
**_bus
) {
588 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
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
);
603 r
= sd_bus_set_address(bus
, "unix:path=/run/systemd/private");
607 r
= sd_bus_start(bus
);
609 return sd_bus_default_system(_bus
);
611 r
= bus_check_peercred(bus
);
615 *_bus
= TAKE_PTR(bus
);
620 int bus_connect_user_systemd(sd_bus
**_bus
) {
621 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
622 _cleanup_free_
char *ee
= NULL
;
628 e
= secure_getenv("XDG_RUNTIME_DIR");
630 return sd_bus_default_user(_bus
);
632 ee
= bus_address_escape(e
);
636 r
= sd_bus_new(&bus
);
640 bus
->address
= strjoin("unix:path=", ee
, "/systemd/private");
644 r
= sd_bus_start(bus
);
646 return sd_bus_default_user(_bus
);
648 r
= bus_check_peercred(bus
);
652 *_bus
= TAKE_PTR(bus
);
657 #define print_property(name, fmt, ...) \
660 printf(fmt "\n", __VA_ARGS__); \
662 printf("%s=" fmt "\n", name, __VA_ARGS__); \
665 int bus_print_property(const char *name
, sd_bus_message
*m
, bool value
, bool all
) {
667 const char *contents
;
673 r
= sd_bus_message_peek_type(m
, &type
, &contents
);
679 case SD_BUS_TYPE_STRING
: {
682 r
= sd_bus_message_read_basic(m
, type
, &s
);
686 if (all
|| !isempty(s
)) {
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]");
698 case SD_BUS_TYPE_BOOLEAN
: {
701 r
= sd_bus_message_read_basic(m
, type
, &b
);
705 print_property(name
, "%s", yes_no(b
));
710 case SD_BUS_TYPE_UINT64
: {
713 r
= sd_bus_message_read_basic(m
, type
, &u
);
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
];
725 t
= format_timestamp(timestamp
, sizeof(timestamp
), u
);
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
;
737 if ((u
& NAMESPACE_FLAGS_ALL
) == 0)
739 else if ((u
& NAMESPACE_FLAGS_ALL
) == NAMESPACE_FLAGS_ALL
)
742 r
= namespace_flags_to_string(u
, &s
);
749 print_property(name
, "%s", result
);
751 } else if (streq(name
, "MountFlags")) {
754 result
= mount_propagation_flags_to_string(u
);
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
);
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");
784 print_property(name
, "%"PRIu64
, u
);
789 case SD_BUS_TYPE_INT64
: {
792 r
= sd_bus_message_read_basic(m
, type
, &i
);
796 print_property(name
, "%"PRIi64
, i
);
801 case SD_BUS_TYPE_UINT32
: {
804 r
= sd_bus_message_read_basic(m
, type
, &u
);
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]");
814 print_property(name
, "%"PRIu32
, u
);
815 } else if (streq(name
, "GID")) {
816 if (u
== GID_INVALID
)
817 print_property(name
, "%s", "[not set]");
819 print_property(name
, "%"PRIu32
, u
);
821 print_property(name
, "%"PRIu32
, u
);
826 case SD_BUS_TYPE_INT32
: {
829 r
= sd_bus_message_read_basic(m
, type
, &i
);
833 print_property(name
, "%"PRIi32
, i
);
837 case SD_BUS_TYPE_DOUBLE
: {
840 r
= sd_bus_message_read_basic(m
, type
, &d
);
844 print_property(name
, "%g", d
);
848 case SD_BUS_TYPE_ARRAY
:
849 if (streq(contents
, "s")) {
853 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, contents
);
857 while ((r
= sd_bus_message_read_basic(m
, SD_BUS_TYPE_STRING
, &str
)) > 0) {
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]");
874 if (first
&& all
&& !value
)
879 r
= sd_bus_message_exit_container(m
);
885 } else if (streq(contents
, "y")) {
889 r
= sd_bus_message_read_array(m
, SD_BUS_TYPE_BYTE
, (const void**) &u
, &n
);
899 for (i
= 0; i
< n
; i
++)
900 printf("%02x", u
[i
]);
907 } else if (streq(contents
, "u")) {
911 r
= sd_bus_message_read_array(m
, SD_BUS_TYPE_UINT32
, (const void**) &u
, &n
);
921 for (i
= 0; i
< n
; i
++)
922 printf("%08x", u
[i
]);
936 int bus_message_print_all_properties(
938 bus_message_print_t func
,
942 Set
**found_properties
) {
948 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "{sv}");
952 while ((r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_DICT_ENTRY
, "sv")) > 0) {
954 const char *contents
;
956 r
= sd_bus_message_read_basic(m
, SD_BUS_TYPE_STRING
, &name
);
960 if (found_properties
) {
961 r
= set_ensure_allocated(found_properties
, &string_hash_ops
);
965 r
= set_put(*found_properties
, name
);
966 if (r
< 0 && r
!= EEXIST
)
970 if (!filter
|| strv_find(filter
, name
)) {
971 r
= sd_bus_message_peek_type(m
, NULL
, &contents
);
975 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_VARIANT
, contents
);
980 r
= func(name
, m
, value
, all
);
982 r
= bus_print_property(name
, m
, value
, all
);
987 printf("%s=[unprintable]\n", name
);
988 /* skip what we didn't read */
989 r
= sd_bus_message_skip(m
, contents
);
994 r
= sd_bus_message_exit_container(m
);
998 r
= sd_bus_message_skip(m
, "v");
1003 r
= sd_bus_message_exit_container(m
);
1010 r
= sd_bus_message_exit_container(m
);
1017 int bus_print_all_properties(
1021 bus_message_print_t func
,
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
;
1034 r
= sd_bus_call_method(bus
,
1037 "org.freedesktop.DBus.Properties",
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
;
1054 r
= sd_bus_message_read_array(m
, SD_BUS_TYPE_BYTE
, &v
, &n
);
1061 memcpy((*p
).bytes
, v
, n
);
1068 static int map_basic(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, unsigned flags
, sd_bus_error
*error
, void *userdata
) {
1072 r
= sd_bus_message_peek_type(m
, &type
, NULL
);
1078 case SD_BUS_TYPE_STRING
: {
1079 const char **p
= userdata
;
1082 r
= sd_bus_message_read_basic(m
, type
, &s
);
1089 if (flags
& BUS_MAP_STRDUP
)
1090 return free_and_strdup((char **) userdata
, s
);
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
);
1104 return strv_free_and_replace(*p
, l
);
1107 case SD_BUS_TYPE_BOOLEAN
: {
1110 r
= sd_bus_message_read_basic(m
, type
, &b
);
1114 if (flags
& BUS_MAP_BOOLEAN_AS_BOOL
)
1115 *(bool*) userdata
= b
;
1117 *(int*) userdata
= b
;
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
);
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
);
1146 case SD_BUS_TYPE_DOUBLE
: {
1147 double d
, *p
= userdata
;
1149 r
= sd_bus_message_read_basic(m
, type
, &d
);
1160 int bus_message_map_all_properties(
1162 const struct bus_properties_map
*map
,
1164 sd_bus_error
*error
,
1172 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "{sv}");
1176 while ((r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_DICT_ENTRY
, "sv")) > 0) {
1177 const struct bus_properties_map
*prop
;
1179 const char *contents
;
1183 r
= sd_bus_message_read_basic(m
, SD_BUS_TYPE_STRING
, &member
);
1187 for (i
= 0, prop
= NULL
; map
[i
].member
; i
++)
1188 if (streq(map
[i
].member
, member
)) {
1194 r
= sd_bus_message_peek_type(m
, NULL
, &contents
);
1198 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_VARIANT
, contents
);
1202 v
= (uint8_t *)userdata
+ prop
->offset
;
1204 r
= prop
->set(sd_bus_message_get_bus(m
), member
, m
, error
, v
);
1206 r
= map_basic(sd_bus_message_get_bus(m
), member
, m
, flags
, error
, v
);
1210 r
= sd_bus_message_exit_container(m
);
1214 r
= sd_bus_message_skip(m
, "v");
1219 r
= sd_bus_message_exit_container(m
);
1226 return sd_bus_message_exit_container(m
);
1229 int bus_message_map_properties_changed(
1231 const struct bus_properties_map
*map
,
1233 sd_bus_error
*error
,
1237 int r
, invalidated
, i
;
1242 r
= bus_message_map_all_properties(m
, map
, flags
, error
, userdata
);
1246 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "s");
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
)) {
1260 r
= sd_bus_message_exit_container(m
);
1267 int bus_map_all_properties(
1269 const char *destination
,
1271 const struct bus_properties_map
*map
,
1273 sd_bus_error
*error
,
1274 sd_bus_message
**reply
,
1277 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1281 assert(destination
);
1284 assert(reply
|| (flags
& BUS_MAP_STRDUP
));
1286 r
= sd_bus_call_method(
1290 "org.freedesktop.DBus.Properties",
1298 r
= bus_message_map_all_properties(m
, map
, flags
, error
, userdata
);
1303 *reply
= sd_bus_message_ref(m
);
1308 int bus_connect_transport(BusTransport transport
, const char *host
, bool user
, sd_bus
**ret
) {
1309 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
1312 assert(transport
>= 0);
1313 assert(transport
< _BUS_TRANSPORT_MAX
);
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
:
1323 r
= sd_bus_default_user(&bus
);
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.");
1331 r
= sd_bus_default_system(&bus
);
1335 case BUS_TRANSPORT_REMOTE
:
1336 r
= sd_bus_open_system_remote(&bus
, host
);
1339 case BUS_TRANSPORT_MACHINE
:
1340 r
= sd_bus_open_system_machine(&bus
, host
);
1344 assert_not_reached("Hmm, unknown transport type.");
1349 r
= sd_bus_set_exit_on_disconnect(bus
, true);
1353 *ret
= TAKE_PTR(bus
);
1358 int bus_connect_transport_systemd(BusTransport transport
, const char *host
, bool user
, sd_bus
**bus
) {
1361 assert(transport
>= 0);
1362 assert(transport
< _BUS_TRANSPORT_MAX
);
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
:
1372 r
= bus_connect_user_systemd(bus
);
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.");
1380 r
= bus_connect_system_systemd(bus
);
1384 case BUS_TRANSPORT_REMOTE
:
1385 r
= sd_bus_open_system_remote(bus
, host
);
1388 case BUS_TRANSPORT_MACHINE
:
1389 r
= sd_bus_open_system_machine(bus
, host
);
1393 assert_not_reached("Hmm, unknown transport type.");
1399 int bus_property_get_bool(
1402 const char *interface
,
1403 const char *property
,
1404 sd_bus_message
*reply
,
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(
1416 const char *interface
,
1417 const char *property
,
1418 sd_bus_message
*value
,
1420 sd_bus_error
*error
) {
1424 r
= sd_bus_message_read(value
, "b", &b
);
1428 *(bool*) userdata
= b
;
1432 int bus_property_get_id128(
1435 const char *interface
,
1436 const char *property
,
1437 sd_bus_message
*reply
,
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);
1446 return sd_bus_message_append_array(reply
, 'y', id
->bytes
, 16);
1449 #if __SIZEOF_SIZE_T__ != 8
1450 int bus_property_get_size(
1453 const char *interface
,
1454 const char *property
,
1455 sd_bus_message
*reply
,
1457 sd_bus_error
*error
) {
1459 uint64_t sz
= *(size_t*) userdata
;
1461 return sd_bus_message_append_basic(reply
, 't', &sz
);
1465 #if __SIZEOF_LONG__ != 8
1466 int bus_property_get_long(
1469 const char *interface
,
1470 const char *property
,
1471 sd_bus_message
*reply
,
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(
1483 const char *interface
,
1484 const char *property
,
1485 sd_bus_message
*reply
,
1487 sd_bus_error
*error
) {
1489 uint64_t ul
= *(unsigned long*) userdata
;
1491 return sd_bus_message_append_basic(reply
, 't', &ul
);
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
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
;
1545 assert_return(b
|| (sender_id
&& external_id
), -EINVAL
);
1546 assert_return(object_path_is_valid(prefix
), -EINVAL
);
1547 assert_return(ret_path
, -EINVAL
);
1550 r
= sd_bus_get_unique_name(b
, &sender_id
);
1556 xsprintf(external_buf
, "%"PRIu64
, ++b
->cookie
);
1557 external_id
= external_buf
;
1560 sender_label
= bus_label_escape(sender_id
);
1564 external_label
= bus_label_escape(external_id
);
1565 if (!external_label
)
1568 p
= strjoin(prefix
, "/", sender_label
, "/", external_label
);
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
) {
1596 char *sender
, *external
;
1598 assert(object_path_is_valid(path
));
1599 assert(object_path_is_valid(prefix
));
1601 assert(ret_external
);
1603 p
= object_path_startswith(path
, prefix
);
1606 *ret_external
= NULL
;
1613 *ret_external
= NULL
;
1617 sender
= bus_label_unescape_n(p
, q
- p
);
1618 external
= bus_label_unescape(q
+ 1);
1619 if (!sender
|| !external
) {
1625 *ret_sender
= sender
;
1626 *ret_external
= external
;
1630 int bus_property_get_rlimit(
1633 const char *interface
,
1634 const char *property
,
1635 sd_bus_message
*reply
,
1637 sd_bus_error
*error
) {
1639 const char *is_soft
;
1648 is_soft
= endswith(property
, "Soft");
1650 rl
= *(struct rlimit
**) userdata
;
1652 x
= is_soft
? rl
->rlim_cur
: rl
->rlim_max
;
1654 struct rlimit buf
= {};
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);
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
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
) {
1684 /* Continues adding after failure, and returns the first failure. */
1686 STRV_FOREACH(i
, l
) {
1689 k
= sd_bus_track_add_name(t
, *i
);
1690 if (k
< 0 && r
>= 0)
1697 int bus_open_system_watch_bind_with_description(sd_bus
**ret
, const char *description
) {
1698 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
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
);
1711 r
= sd_bus_set_description(bus
, description
);
1716 e
= secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1718 e
= DEFAULT_SYSTEM_BUS_ADDRESS
;
1720 r
= sd_bus_set_address(bus
, e
);
1724 r
= sd_bus_set_bus_client(bus
, true);
1728 r
= sd_bus_set_trusted(bus
, true);
1732 r
= sd_bus_negotiate_creds(bus
, true, SD_BUS_CREDS_UID
|SD_BUS_CREDS_EUID
|SD_BUS_CREDS_EFFECTIVE_CAPS
);
1736 r
= sd_bus_set_watch_bind(bus
, true);
1740 r
= sd_bus_set_connected_signal(bus
, true);
1744 r
= sd_bus_start(bus
);
1748 *ret
= TAKE_PTR(bus
);
1753 struct request_name_data
{
1761 static void request_name_destroy_callback(void *userdata
) {
1762 struct request_name_data
*data
= userdata
;
1765 assert(data
->n_ref
> 0);
1767 log_info("%s n_ref=%u", __func__
, data
->n_ref
);
1770 if (data
->n_ref
== 0)
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
;
1781 assert(data
->n_ref
> 0);
1783 e
= sd_bus_message_get_error(m
);
1785 log_error_errno(sd_bus_error_get_errno(e
), "Failed to reload DBus configuration: %s", e
->message
);
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
);
1792 log_error_errno(r
, "Failed to request name: %m");
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
;
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",
1814 bus_enter_closing(sd_bus_message_get_bus(m
));
1818 log_debug_errno(sd_bus_error_get_errno(e
),
1819 "Unable to request name, will retry after reloading DBus configuration: %s",
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
),
1831 "org.freedesktop.DBus",
1832 "/org/freedesktop/DBus",
1833 "org.freedesktop.DBus",
1835 reload_dbus_handler
,
1838 log_error_errno(r
, "Failed to reload DBus configuration: %m");
1839 bus_enter_closing(sd_bus_message_get_bus(m
));
1844 assert_se(sd_bus_slot_set_destroy_callback(slot
, request_name_destroy_callback
) >= 0);
1846 r
= sd_bus_slot_set_floating(slot
, true);
1853 r
= sd_bus_message_read(m
, "u", &ret
);
1859 case BUS_NAME_ALREADY_OWNER
:
1860 log_debug("Already owner of requested service name, ignoring.");
1863 case BUS_NAME_IN_QUEUE
:
1864 log_debug("In queue for requested service name.");
1867 case BUS_NAME_PRIMARY_OWNER
:
1868 log_debug("Successfully acquired requested service name.");
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
));
1877 log_debug("Unexpected response from RequestName(), failing connection.");
1878 bus_enter_closing(sd_bus_message_get_bus(m
));
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
;
1887 data
= new(struct request_name_data
, 1);
1891 *data
= (struct request_name_data
) {
1895 .userdata
= userdata
,
1898 r
= sd_bus_request_name_async(bus
, &slot
, name
, flags
, request_name_handler_may_reload_dbus
, data
);
1902 assert_se(sd_bus_slot_set_destroy_callback(slot
, request_name_destroy_callback
) >= 0);
1906 *ret_slot
= TAKE_PTR(slot
);
1908 r
= sd_bus_slot_set_floating(slot
, true);
1916 int bus_reply_pair_array(sd_bus_message
*m
, char **l
) {
1917 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1923 /* Reply to the specified message with a message containing a dictionary put together from the specified
1926 r
= sd_bus_message_new_method_return(m
, &reply
);
1930 r
= sd_bus_message_open_container(reply
, 'a', "{ss}");
1934 STRV_FOREACH_PAIR(k
, v
, l
) {
1935 r
= sd_bus_message_append(reply
, "{ss}", *k
, *v
);
1940 r
= sd_bus_message_close_container(reply
);
1944 return sd_bus_send(NULL
, reply
, NULL
);