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
;
322 sd_bus_message_handler_t callback
;
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
);
344 static int async_polkit_callback(sd_bus_message
*reply
, void *userdata
, sd_bus_error
*error
) {
345 _cleanup_(sd_bus_error_free
) sd_bus_error error_buffer
= SD_BUS_ERROR_NULL
;
346 AsyncPolkitQuery
*q
= userdata
;
352 q
->slot
= sd_bus_slot_unref(q
->slot
);
353 q
->reply
= sd_bus_message_ref(reply
);
355 r
= sd_bus_message_rewind(q
->request
, true);
357 r
= sd_bus_reply_method_errno(q
->request
, r
, NULL
);
361 r
= q
->callback(q
->request
, q
->userdata
, &error_buffer
);
362 r
= bus_maybe_reply_error(q
->request
, r
, &error_buffer
);
365 async_polkit_query_free(q
);
372 int bus_verify_polkit_async(
373 sd_bus_message
*call
,
376 const char **details
,
380 sd_bus_error
*error
) {
383 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*pk
= NULL
;
385 const char *sender
, **k
, **v
;
386 sd_bus_message_handler_t callback
;
396 r
= check_good_user(call
, good_user
);
401 q
= hashmap_get(*registry
, call
);
403 int authorized
, challenge
;
405 /* This is the second invocation of this function, and
406 * there's already a response from polkit, let's
410 if (sd_bus_message_is_method_error(q
->reply
, NULL
)) {
411 const sd_bus_error
*e
;
413 /* Copy error from polkit reply */
414 e
= sd_bus_message_get_error(q
->reply
);
415 sd_bus_error_copy(error
, e
);
417 /* Treat no PK available as access denied */
418 if (sd_bus_error_has_name(e
, SD_BUS_ERROR_SERVICE_UNKNOWN
))
421 return -sd_bus_error_get_errno(e
);
424 r
= sd_bus_message_enter_container(q
->reply
, 'r', "bba{ss}");
426 r
= sd_bus_message_read(q
->reply
, "bb", &authorized
, &challenge
);
435 return sd_bus_error_set(error
, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED
, "Interactive authentication required.");
441 r
= sd_bus_query_sender_privilege(call
, capability
);
448 if (sd_bus_get_current_message(call
->bus
) != call
)
451 callback
= sd_bus_get_current_handler(call
->bus
);
455 userdata
= sd_bus_get_current_userdata(call
->bus
);
457 sender
= sd_bus_message_get_sender(call
);
461 c
= sd_bus_message_get_allow_interactive_authorization(call
);
467 r
= hashmap_ensure_allocated(registry
, NULL
);
471 r
= sd_bus_message_new_method_call(
474 "org.freedesktop.PolicyKit1",
475 "/org/freedesktop/PolicyKit1/Authority",
476 "org.freedesktop.PolicyKit1.Authority",
477 "CheckAuthorization");
481 r
= sd_bus_message_append(
484 "system-bus-name", 1, "name", "s", sender
,
489 r
= sd_bus_message_open_container(pk
, 'a', "{ss}");
493 STRV_FOREACH_PAIR(k
, v
, details
) {
494 r
= sd_bus_message_append(pk
, "{ss}", *k
, *v
);
499 r
= sd_bus_message_close_container(pk
);
503 r
= sd_bus_message_append(pk
, "us", !!interactive
, NULL
);
507 q
= new0(AsyncPolkitQuery
, 1);
511 q
->request
= sd_bus_message_ref(call
);
512 q
->callback
= callback
;
513 q
->userdata
= userdata
;
515 r
= hashmap_put(*registry
, call
, q
);
517 async_polkit_query_free(q
);
521 q
->registry
= *registry
;
523 r
= sd_bus_call_async(call
->bus
, &q
->slot
, pk
, async_polkit_callback
, q
, 0);
525 async_polkit_query_free(q
);
535 void bus_verify_polkit_async_registry_free(Hashmap
*registry
) {
537 hashmap_free_with_destructor(registry
, async_polkit_query_free
);
541 int bus_check_peercred(sd_bus
*c
) {
547 fd
= sd_bus_get_fd(c
);
551 r
= getpeercred(fd
, &ucred
);
555 if (ucred
.uid
!= 0 && ucred
.uid
!= geteuid())
561 int bus_connect_system_systemd(sd_bus
**_bus
) {
562 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
568 return sd_bus_default_system(_bus
);
570 /* If we are root then let's talk directly to the system
571 * instance, instead of going via the bus */
573 r
= sd_bus_new(&bus
);
577 r
= sd_bus_set_address(bus
, "unix:path=/run/systemd/private");
581 r
= sd_bus_start(bus
);
583 return sd_bus_default_system(_bus
);
585 r
= bus_check_peercred(bus
);
589 *_bus
= TAKE_PTR(bus
);
594 int bus_connect_user_systemd(sd_bus
**_bus
) {
595 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
596 _cleanup_free_
char *ee
= NULL
;
602 e
= secure_getenv("XDG_RUNTIME_DIR");
604 return sd_bus_default_user(_bus
);
606 ee
= bus_address_escape(e
);
610 r
= sd_bus_new(&bus
);
614 bus
->address
= strjoin("unix:path=", ee
, "/systemd/private");
618 r
= sd_bus_start(bus
);
620 return sd_bus_default_user(_bus
);
622 r
= bus_check_peercred(bus
);
626 *_bus
= TAKE_PTR(bus
);
631 #define print_property(name, fmt, ...) \
634 printf(fmt "\n", __VA_ARGS__); \
636 printf("%s=" fmt "\n", name, __VA_ARGS__); \
639 int bus_print_property(const char *name
, sd_bus_message
*m
, bool value
, bool all
) {
641 const char *contents
;
647 r
= sd_bus_message_peek_type(m
, &type
, &contents
);
653 case SD_BUS_TYPE_STRING
: {
656 r
= sd_bus_message_read_basic(m
, type
, &s
);
660 if (all
|| !isempty(s
)) {
663 /* This property has a single value, so we need to take
664 * care not to print a new line, everything else is OK. */
665 good
= !strchr(s
, '\n');
666 print_property(name
, "%s", good
? s
: "[unprintable]");
672 case SD_BUS_TYPE_BOOLEAN
: {
675 r
= sd_bus_message_read_basic(m
, type
, &b
);
679 print_property(name
, "%s", yes_no(b
));
684 case SD_BUS_TYPE_UINT64
: {
687 r
= sd_bus_message_read_basic(m
, type
, &u
);
691 /* Yes, heuristics! But we can change this check
692 * should it turn out to not be sufficient */
694 if (endswith(name
, "Timestamp") ||
695 STR_IN_SET(name
, "NextElapseUSecRealtime", "LastTriggerUSec", "TimeUSec", "RTCTimeUSec")) {
696 char timestamp
[FORMAT_TIMESTAMP_MAX
];
699 t
= format_timestamp(timestamp
, sizeof(timestamp
), u
);
701 print_property(name
, "%s", strempty(t
));
703 } else if (strstr(name
, "USec")) {
704 char timespan
[FORMAT_TIMESPAN_MAX
];
706 print_property(name
, "%s", format_timespan(timespan
, sizeof(timespan
), u
, 0));
707 } else if (streq(name
, "RestrictNamespaces")) {
708 _cleanup_free_
char *s
= NULL
;
711 if ((u
& NAMESPACE_FLAGS_ALL
) == 0)
713 else if ((u
& NAMESPACE_FLAGS_ALL
) == NAMESPACE_FLAGS_ALL
)
716 r
= namespace_flags_to_string(u
, &s
);
723 print_property(name
, "%s", result
);
725 } else if (streq(name
, "MountFlags")) {
728 result
= mount_propagation_flags_to_string(u
);
732 print_property(name
, "%s", result
);
734 } else if (STR_IN_SET(name
, "CapabilityBoundingSet", "AmbientCapabilities")) {
735 _cleanup_free_
char *s
= NULL
;
737 r
= capability_set_to_string_alloc(u
, &s
);
741 print_property(name
, "%s", s
);
743 } else if ((STR_IN_SET(name
, "CPUWeight", "StartupCPUWeight", "IOWeight", "StartupIOWeight") && u
== CGROUP_WEIGHT_INVALID
) ||
744 (STR_IN_SET(name
, "CPUShares", "StartupCPUShares") && u
== CGROUP_CPU_SHARES_INVALID
) ||
745 (STR_IN_SET(name
, "BlockIOWeight", "StartupBlockIOWeight") && u
== CGROUP_BLKIO_WEIGHT_INVALID
) ||
746 (STR_IN_SET(name
, "MemoryCurrent", "TasksCurrent") && u
== (uint64_t) -1) ||
747 (endswith(name
, "NSec") && u
== (uint64_t) -1))
749 print_property(name
, "%s", "[not set]");
751 else if ((STR_IN_SET(name
, "MemoryLow", "MemoryHigh", "MemoryMax", "MemorySwapMax", "MemoryLimit") && u
== CGROUP_LIMIT_MAX
) ||
752 (STR_IN_SET(name
, "TasksMax", "DefaultTasksMax") && u
== (uint64_t) -1) ||
753 (startswith(name
, "Limit") && u
== (uint64_t) -1) ||
754 (startswith(name
, "DefaultLimit") && u
== (uint64_t) -1))
756 print_property(name
, "%s", "infinity");
758 print_property(name
, "%"PRIu64
, u
);
763 case SD_BUS_TYPE_INT64
: {
766 r
= sd_bus_message_read_basic(m
, type
, &i
);
770 print_property(name
, "%"PRIi64
, i
);
775 case SD_BUS_TYPE_UINT32
: {
778 r
= sd_bus_message_read_basic(m
, type
, &u
);
782 if (strstr(name
, "UMask") || strstr(name
, "Mode"))
783 print_property(name
, "%04o", u
);
784 else if (streq(name
, "UID")) {
785 if (u
== UID_INVALID
)
786 print_property(name
, "%s", "[not set]");
788 print_property(name
, "%"PRIu32
, u
);
789 } else if (streq(name
, "GID")) {
790 if (u
== GID_INVALID
)
791 print_property(name
, "%s", "[not set]");
793 print_property(name
, "%"PRIu32
, u
);
795 print_property(name
, "%"PRIu32
, u
);
800 case SD_BUS_TYPE_INT32
: {
803 r
= sd_bus_message_read_basic(m
, type
, &i
);
807 print_property(name
, "%"PRIi32
, i
);
811 case SD_BUS_TYPE_DOUBLE
: {
814 r
= sd_bus_message_read_basic(m
, type
, &d
);
818 print_property(name
, "%g", d
);
822 case SD_BUS_TYPE_ARRAY
:
823 if (streq(contents
, "s")) {
827 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, contents
);
831 while ((r
= sd_bus_message_read_basic(m
, SD_BUS_TYPE_STRING
, &str
)) > 0) {
837 /* This property has multiple space-separated values, so
838 * neither spaces nor newlines can be allowed in a value. */
839 good
= str
[strcspn(str
, " \n")] == '\0';
841 printf("%s%s", first
? "" : " ", good
? str
: "[unprintable]");
848 if (first
&& all
&& !value
)
853 r
= sd_bus_message_exit_container(m
);
859 } else if (streq(contents
, "y")) {
863 r
= sd_bus_message_read_array(m
, SD_BUS_TYPE_BYTE
, (const void**) &u
, &n
);
873 for (i
= 0; i
< n
; i
++)
874 printf("%02x", u
[i
]);
881 } else if (streq(contents
, "u")) {
885 r
= sd_bus_message_read_array(m
, SD_BUS_TYPE_UINT32
, (const void**) &u
, &n
);
895 for (i
= 0; i
< n
; i
++)
896 printf("%08x", u
[i
]);
910 int bus_message_print_all_properties(
912 bus_message_print_t func
,
916 Set
**found_properties
) {
922 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "{sv}");
926 while ((r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_DICT_ENTRY
, "sv")) > 0) {
928 const char *contents
;
930 r
= sd_bus_message_read_basic(m
, SD_BUS_TYPE_STRING
, &name
);
934 if (found_properties
) {
935 r
= set_ensure_allocated(found_properties
, &string_hash_ops
);
939 r
= set_put(*found_properties
, name
);
940 if (r
< 0 && r
!= -EEXIST
)
944 if (!filter
|| strv_find(filter
, name
)) {
945 r
= sd_bus_message_peek_type(m
, NULL
, &contents
);
949 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_VARIANT
, contents
);
954 r
= func(name
, m
, value
, all
);
956 r
= bus_print_property(name
, m
, value
, all
);
961 printf("%s=[unprintable]\n", name
);
962 /* skip what we didn't read */
963 r
= sd_bus_message_skip(m
, contents
);
968 r
= sd_bus_message_exit_container(m
);
972 r
= sd_bus_message_skip(m
, "v");
977 r
= sd_bus_message_exit_container(m
);
984 r
= sd_bus_message_exit_container(m
);
991 int bus_print_all_properties(
995 bus_message_print_t func
,
999 Set
**found_properties
) {
1001 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1002 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1008 r
= sd_bus_call_method(bus
,
1011 "org.freedesktop.DBus.Properties",
1019 return bus_message_print_all_properties(reply
, func
, filter
, value
, all
, found_properties
);
1022 int bus_map_id128(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
1023 sd_id128_t
*p
= userdata
;
1028 r
= sd_bus_message_read_array(m
, SD_BUS_TYPE_BYTE
, &v
, &n
);
1035 memcpy((*p
).bytes
, v
, n
);
1042 static int map_basic(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, unsigned flags
, sd_bus_error
*error
, void *userdata
) {
1046 r
= sd_bus_message_peek_type(m
, &type
, NULL
);
1052 case SD_BUS_TYPE_STRING
: {
1053 const char **p
= userdata
;
1056 r
= sd_bus_message_read_basic(m
, type
, &s
);
1063 if (flags
& BUS_MAP_STRDUP
)
1064 return free_and_strdup((char **) userdata
, s
);
1070 case SD_BUS_TYPE_ARRAY
: {
1071 _cleanup_strv_free_
char **l
= NULL
;
1072 char ***p
= userdata
;
1074 r
= bus_message_read_strv_extend(m
, &l
);
1078 return strv_free_and_replace(*p
, l
);
1081 case SD_BUS_TYPE_BOOLEAN
: {
1084 r
= sd_bus_message_read_basic(m
, type
, &b
);
1088 if (flags
& BUS_MAP_BOOLEAN_AS_BOOL
)
1089 *(bool*) userdata
= b
;
1091 *(int*) userdata
= b
;
1096 case SD_BUS_TYPE_INT32
:
1097 case SD_BUS_TYPE_UINT32
: {
1098 uint32_t u
, *p
= userdata
;
1100 r
= sd_bus_message_read_basic(m
, type
, &u
);
1108 case SD_BUS_TYPE_INT64
:
1109 case SD_BUS_TYPE_UINT64
: {
1110 uint64_t t
, *p
= userdata
;
1112 r
= sd_bus_message_read_basic(m
, type
, &t
);
1120 case SD_BUS_TYPE_DOUBLE
: {
1121 double d
, *p
= userdata
;
1123 r
= sd_bus_message_read_basic(m
, type
, &d
);
1134 int bus_message_map_all_properties(
1136 const struct bus_properties_map
*map
,
1138 sd_bus_error
*error
,
1146 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "{sv}");
1150 while ((r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_DICT_ENTRY
, "sv")) > 0) {
1151 const struct bus_properties_map
*prop
;
1153 const char *contents
;
1157 r
= sd_bus_message_read_basic(m
, SD_BUS_TYPE_STRING
, &member
);
1161 for (i
= 0, prop
= NULL
; map
[i
].member
; i
++)
1162 if (streq(map
[i
].member
, member
)) {
1168 r
= sd_bus_message_peek_type(m
, NULL
, &contents
);
1172 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_VARIANT
, contents
);
1176 v
= (uint8_t *)userdata
+ prop
->offset
;
1178 r
= prop
->set(sd_bus_message_get_bus(m
), member
, m
, error
, v
);
1180 r
= map_basic(sd_bus_message_get_bus(m
), member
, m
, flags
, error
, v
);
1184 r
= sd_bus_message_exit_container(m
);
1188 r
= sd_bus_message_skip(m
, "v");
1193 r
= sd_bus_message_exit_container(m
);
1200 return sd_bus_message_exit_container(m
);
1203 int bus_message_map_properties_changed(
1205 const struct bus_properties_map
*map
,
1207 sd_bus_error
*error
,
1211 int r
, invalidated
, i
;
1216 r
= bus_message_map_all_properties(m
, map
, flags
, error
, userdata
);
1220 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "s");
1225 while ((r
= sd_bus_message_read_basic(m
, SD_BUS_TYPE_STRING
, &member
)) > 0)
1226 for (i
= 0; map
[i
].member
; i
++)
1227 if (streq(map
[i
].member
, member
)) {
1234 r
= sd_bus_message_exit_container(m
);
1241 int bus_map_all_properties(
1243 const char *destination
,
1245 const struct bus_properties_map
*map
,
1247 sd_bus_error
*error
,
1248 sd_bus_message
**reply
,
1251 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1255 assert(destination
);
1258 assert(reply
|| (flags
& BUS_MAP_STRDUP
));
1260 r
= sd_bus_call_method(
1264 "org.freedesktop.DBus.Properties",
1272 r
= bus_message_map_all_properties(m
, map
, flags
, error
, userdata
);
1277 *reply
= sd_bus_message_ref(m
);
1282 int bus_connect_transport(BusTransport transport
, const char *host
, bool user
, sd_bus
**ret
) {
1283 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
1286 assert(transport
>= 0);
1287 assert(transport
< _BUS_TRANSPORT_MAX
);
1290 assert_return((transport
== BUS_TRANSPORT_LOCAL
) == !host
, -EINVAL
);
1291 assert_return(transport
== BUS_TRANSPORT_LOCAL
|| !user
, -EOPNOTSUPP
);
1293 switch (transport
) {
1295 case BUS_TRANSPORT_LOCAL
:
1297 r
= sd_bus_default_user(&bus
);
1299 if (sd_booted() <= 0) {
1300 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1301 log_error("System has not been booted with systemd as init system (PID 1). Can't operate.");
1305 r
= sd_bus_default_system(&bus
);
1309 case BUS_TRANSPORT_REMOTE
:
1310 r
= sd_bus_open_system_remote(&bus
, host
);
1313 case BUS_TRANSPORT_MACHINE
:
1314 r
= sd_bus_open_system_machine(&bus
, host
);
1318 assert_not_reached("Hmm, unknown transport type.");
1323 r
= sd_bus_set_exit_on_disconnect(bus
, true);
1327 *ret
= TAKE_PTR(bus
);
1332 int bus_connect_transport_systemd(BusTransport transport
, const char *host
, bool user
, sd_bus
**bus
) {
1335 assert(transport
>= 0);
1336 assert(transport
< _BUS_TRANSPORT_MAX
);
1339 assert_return((transport
== BUS_TRANSPORT_LOCAL
) == !host
, -EINVAL
);
1340 assert_return(transport
== BUS_TRANSPORT_LOCAL
|| !user
, -EOPNOTSUPP
);
1342 switch (transport
) {
1344 case BUS_TRANSPORT_LOCAL
:
1346 r
= bus_connect_user_systemd(bus
);
1348 if (sd_booted() <= 0) {
1349 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1350 log_error("System has not been booted with systemd as init system (PID 1). Can't operate.");
1354 r
= bus_connect_system_systemd(bus
);
1358 case BUS_TRANSPORT_REMOTE
:
1359 r
= sd_bus_open_system_remote(bus
, host
);
1362 case BUS_TRANSPORT_MACHINE
:
1363 r
= sd_bus_open_system_machine(bus
, host
);
1367 assert_not_reached("Hmm, unknown transport type.");
1373 int bus_property_get_bool(
1376 const char *interface
,
1377 const char *property
,
1378 sd_bus_message
*reply
,
1380 sd_bus_error
*error
) {
1382 int b
= *(bool*) userdata
;
1384 return sd_bus_message_append_basic(reply
, 'b', &b
);
1387 int bus_property_set_bool(
1390 const char *interface
,
1391 const char *property
,
1392 sd_bus_message
*value
,
1394 sd_bus_error
*error
) {
1398 r
= sd_bus_message_read(value
, "b", &b
);
1402 *(bool*) userdata
= b
;
1406 int bus_property_get_id128(
1409 const char *interface
,
1410 const char *property
,
1411 sd_bus_message
*reply
,
1413 sd_bus_error
*error
) {
1415 sd_id128_t
*id
= userdata
;
1417 if (sd_id128_is_null(*id
)) /* Add an empty array if the ID is zero */
1418 return sd_bus_message_append(reply
, "ay", 0);
1420 return sd_bus_message_append_array(reply
, 'y', id
->bytes
, 16);
1423 #if __SIZEOF_SIZE_T__ != 8
1424 int bus_property_get_size(
1427 const char *interface
,
1428 const char *property
,
1429 sd_bus_message
*reply
,
1431 sd_bus_error
*error
) {
1433 uint64_t sz
= *(size_t*) userdata
;
1435 return sd_bus_message_append_basic(reply
, 't', &sz
);
1439 #if __SIZEOF_LONG__ != 8
1440 int bus_property_get_long(
1443 const char *interface
,
1444 const char *property
,
1445 sd_bus_message
*reply
,
1447 sd_bus_error
*error
) {
1449 int64_t l
= *(long*) userdata
;
1451 return sd_bus_message_append_basic(reply
, 'x', &l
);
1454 int bus_property_get_ulong(
1457 const char *interface
,
1458 const char *property
,
1459 sd_bus_message
*reply
,
1461 sd_bus_error
*error
) {
1463 uint64_t ul
= *(unsigned long*) userdata
;
1465 return sd_bus_message_append_basic(reply
, 't', &ul
);
1469 int bus_log_parse_error(int r
) {
1470 return log_error_errno(r
, "Failed to parse bus message: %m");
1473 int bus_log_create_error(int r
) {
1474 return log_error_errno(r
, "Failed to create bus message: %m");
1478 * bus_path_encode_unique() - encode unique object path
1479 * @b: bus connection or NULL
1480 * @prefix: object path prefix
1481 * @sender_id: unique-name of client, or NULL
1482 * @external_id: external ID to be chosen by client, or NULL
1483 * @ret_path: storage for encoded object path pointer
1485 * Whenever we provide a bus API that allows clients to create and manage
1486 * server-side objects, we need to provide a unique name for these objects. If
1487 * we let the server choose the name, we suffer from a race condition: If a
1488 * client creates an object asynchronously, it cannot destroy that object until
1489 * it received the method reply. It cannot know the name of the new object,
1490 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
1492 * Therefore, many APIs allow the client to choose the unique name for newly
1493 * created objects. There're two problems to solve, though:
1494 * 1) Object names are usually defined via dbus object paths, which are
1495 * usually globally namespaced. Therefore, multiple clients must be able
1496 * to choose unique object names without interference.
1497 * 2) If multiple libraries share the same bus connection, they must be
1498 * able to choose unique object names without interference.
1499 * The first problem is solved easily by prefixing a name with the
1500 * unique-bus-name of a connection. The server side must enforce this and
1501 * reject any other name. The second problem is solved by providing unique
1502 * suffixes from within sd-bus.
1504 * This helper allows clients to create unique object-paths. It uses the
1505 * template '/prefix/sender_id/external_id' and returns the new path in
1506 * @ret_path (must be freed by the caller).
1507 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
1508 * NULL, this function allocates a unique suffix via @b (by requesting a new
1509 * cookie). If both @sender_id and @external_id are given, @b can be passed as
1512 * Returns: 0 on success, negative error code on failure.
1514 int bus_path_encode_unique(sd_bus
*b
, const char *prefix
, const char *sender_id
, const char *external_id
, char **ret_path
) {
1515 _cleanup_free_
char *sender_label
= NULL
, *external_label
= NULL
;
1516 char external_buf
[DECIMAL_STR_MAX(uint64_t)], *p
;
1519 assert_return(b
|| (sender_id
&& external_id
), -EINVAL
);
1520 assert_return(object_path_is_valid(prefix
), -EINVAL
);
1521 assert_return(ret_path
, -EINVAL
);
1524 r
= sd_bus_get_unique_name(b
, &sender_id
);
1530 xsprintf(external_buf
, "%"PRIu64
, ++b
->cookie
);
1531 external_id
= external_buf
;
1534 sender_label
= bus_label_escape(sender_id
);
1538 external_label
= bus_label_escape(external_id
);
1539 if (!external_label
)
1542 p
= strjoin(prefix
, "/", sender_label
, "/", external_label
);
1551 * bus_path_decode_unique() - decode unique object path
1552 * @path: object path to decode
1553 * @prefix: object path prefix
1554 * @ret_sender: output parameter for sender-id label
1555 * @ret_external: output parameter for external-id label
1557 * This does the reverse of bus_path_encode_unique() (see its description for
1558 * details). Both trailing labels, sender-id and external-id, are unescaped and
1559 * returned in the given output parameters (the caller must free them).
1561 * Note that this function returns 0 if the path does not match the template
1562 * (see bus_path_encode_unique()), 1 if it matched.
1564 * Returns: Negative error code on failure, 0 if the given object path does not
1565 * match the template (return parameters are set to NULL), 1 if it was
1566 * parsed successfully (return parameters contain allocated labels).
1568 int bus_path_decode_unique(const char *path
, const char *prefix
, char **ret_sender
, char **ret_external
) {
1570 char *sender
, *external
;
1572 assert(object_path_is_valid(path
));
1573 assert(object_path_is_valid(prefix
));
1575 assert(ret_external
);
1577 p
= object_path_startswith(path
, prefix
);
1580 *ret_external
= NULL
;
1587 *ret_external
= NULL
;
1591 sender
= bus_label_unescape_n(p
, q
- p
);
1592 external
= bus_label_unescape(q
+ 1);
1593 if (!sender
|| !external
) {
1599 *ret_sender
= sender
;
1600 *ret_external
= external
;
1604 int bus_property_get_rlimit(
1607 const char *interface
,
1608 const char *property
,
1609 sd_bus_message
*reply
,
1611 sd_bus_error
*error
) {
1613 const char *is_soft
;
1622 is_soft
= endswith(property
, "Soft");
1624 rl
= *(struct rlimit
**) userdata
;
1626 x
= is_soft
? rl
->rlim_cur
: rl
->rlim_max
;
1628 struct rlimit buf
= {};
1632 /* Chop off "Soft" suffix */
1633 s
= is_soft
? strndupa(property
, is_soft
- property
) : property
;
1635 /* Skip over any prefix, such as "Default" */
1636 assert_se(p
= strstr(s
, "Limit"));
1638 z
= rlimit_from_string(p
+ 5);
1641 (void) getrlimit(z
, &buf
);
1642 x
= is_soft
? buf
.rlim_cur
: buf
.rlim_max
;
1645 /* rlim_t might have different sizes, let's map RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on all
1647 u
= x
== RLIM_INFINITY
? (uint64_t) -1 : (uint64_t) x
;
1649 return sd_bus_message_append(reply
, "t", u
);
1652 int bus_track_add_name_many(sd_bus_track
*t
, char **l
) {
1658 /* Continues adding after failure, and returns the first failure. */
1660 STRV_FOREACH(i
, l
) {
1663 k
= sd_bus_track_add_name(t
, *i
);
1664 if (k
< 0 && r
>= 0)
1671 int bus_open_system_watch_bind_with_description(sd_bus
**ret
, const char *description
) {
1672 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
1678 /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal turned on. */
1680 r
= sd_bus_new(&bus
);
1685 r
= sd_bus_set_description(bus
, description
);
1690 e
= secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1692 e
= DEFAULT_SYSTEM_BUS_ADDRESS
;
1694 r
= sd_bus_set_address(bus
, e
);
1698 r
= sd_bus_set_bus_client(bus
, true);
1702 r
= sd_bus_set_trusted(bus
, true);
1706 r
= sd_bus_negotiate_creds(bus
, true, SD_BUS_CREDS_UID
|SD_BUS_CREDS_EUID
|SD_BUS_CREDS_EFFECTIVE_CAPS
);
1710 r
= sd_bus_set_watch_bind(bus
, true);
1714 r
= sd_bus_set_connected_signal(bus
, true);
1718 r
= sd_bus_start(bus
);
1722 *ret
= TAKE_PTR(bus
);
1727 struct request_name_data
{
1735 static void request_name_destroy_callback(void *userdata
) {
1736 struct request_name_data
*data
= userdata
;
1739 assert(data
->n_ref
> 0);
1741 log_info("%s n_ref=%u", __func__
, data
->n_ref
);
1744 if (data
->n_ref
== 0)
1748 static int reload_dbus_handler(sd_bus_message
*m
, void *userdata
, sd_bus_error
*ret_error
) {
1749 struct request_name_data
*data
= userdata
;
1750 const sd_bus_error
*e
;
1755 assert(data
->n_ref
> 0);
1757 e
= sd_bus_message_get_error(m
);
1759 log_error_errno(sd_bus_error_get_errno(e
), "Failed to reload DBus configuration: %s", e
->message
);
1763 /* Here, use the default request name handler to avoid an infinite loop of reloading and requesting. */
1764 r
= sd_bus_request_name_async(sd_bus_message_get_bus(m
), NULL
, data
->name
, data
->flags
, NULL
, data
->userdata
);
1766 log_error_errno(r
, "Failed to request name: %m");
1771 static int request_name_handler_may_reload_dbus(sd_bus_message
*m
, void *userdata
, sd_bus_error
*ret_error
) {
1772 struct request_name_data
*data
= userdata
;
1779 if (sd_bus_message_is_method_error(m
, NULL
)) {
1780 const sd_bus_error
*e
= sd_bus_message_get_error(m
);
1781 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot
= NULL
;
1783 if (!sd_bus_error_has_name(e
, SD_BUS_ERROR_ACCESS_DENIED
)) {
1784 log_debug_errno(sd_bus_error_get_errno(e
),
1785 "Unable to request name, failing connection: %s",
1788 bus_enter_closing(sd_bus_message_get_bus(m
));
1792 log_debug_errno(sd_bus_error_get_errno(e
),
1793 "Unable to request name, will retry after reloading DBus configuration: %s",
1796 /* If systemd-timesyncd.service enables DynamicUser= and dbus.service
1797 * started before the dynamic user is realized, then the DBus policy
1798 * about timesyncd has not been enabled yet. So, let's try to reload
1799 * DBus configuration, and after that request the name again. Note that it
1800 * seems that no privileges are necessary to call the following method. */
1802 r
= sd_bus_call_method_async(
1803 sd_bus_message_get_bus(m
),
1805 "org.freedesktop.DBus",
1806 "/org/freedesktop/DBus",
1807 "org.freedesktop.DBus",
1809 reload_dbus_handler
,
1812 log_error_errno(r
, "Failed to reload DBus configuration: %m");
1813 bus_enter_closing(sd_bus_message_get_bus(m
));
1818 assert_se(sd_bus_slot_set_destroy_callback(slot
, request_name_destroy_callback
) >= 0);
1820 r
= sd_bus_slot_set_floating(slot
, true);
1827 r
= sd_bus_message_read(m
, "u", &ret
);
1833 case BUS_NAME_ALREADY_OWNER
:
1834 log_debug("Already owner of requested service name, ignoring.");
1837 case BUS_NAME_IN_QUEUE
:
1838 log_debug("In queue for requested service name.");
1841 case BUS_NAME_PRIMARY_OWNER
:
1842 log_debug("Successfully acquired requested service name.");
1845 case BUS_NAME_EXISTS
:
1846 log_debug("Requested service name already owned, failing connection.");
1847 bus_enter_closing(sd_bus_message_get_bus(m
));
1851 log_debug("Unexpected response from RequestName(), failing connection.");
1852 bus_enter_closing(sd_bus_message_get_bus(m
));
1856 int bus_request_name_async_may_reload_dbus(sd_bus
*bus
, sd_bus_slot
**ret_slot
, const char *name
, uint64_t flags
, void *userdata
) {
1857 _cleanup_free_
struct request_name_data
*data
= NULL
;
1858 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot
= NULL
;
1861 data
= new(struct request_name_data
, 1);
1865 *data
= (struct request_name_data
) {
1869 .userdata
= userdata
,
1872 r
= sd_bus_request_name_async(bus
, &slot
, name
, flags
, request_name_handler_may_reload_dbus
, data
);
1876 assert_se(sd_bus_slot_set_destroy_callback(slot
, request_name_destroy_callback
) >= 0);
1880 *ret_slot
= TAKE_PTR(slot
);
1882 r
= sd_bus_slot_set_floating(slot
, true);
1890 int bus_reply_pair_array(sd_bus_message
*m
, char **l
) {
1891 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1897 /* Reply to the specified message with a message containing a dictionary put together from the specified
1900 r
= sd_bus_message_new_method_return(m
, &reply
);
1904 r
= sd_bus_message_open_container(reply
, 'a', "{ss}");
1908 STRV_FOREACH_PAIR(k
, v
, l
) {
1909 r
= sd_bus_message_append(reply
, "{ss}", *k
, *v
);
1914 r
= sd_bus_message_close_container(reply
);
1918 return sd_bus_send(NULL
, reply
, NULL
);