1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2013 Lennart Poettering
14 #include <sys/ioctl.h>
15 #include <sys/resource.h>
16 #include <sys/socket.h>
19 #include "sd-bus-protocol.h"
21 #include "sd-daemon.h"
25 #include "alloc-util.h"
26 #include "bus-internal.h"
27 #include "bus-label.h"
28 #include "bus-message.h"
31 #include "cgroup-util.h"
36 #include "mount-util.h"
38 #include "parse-util.h"
39 #include "proc-cmdline.h"
40 #include "rlimit-util.h"
41 #include "stdio-util.h"
43 #include "user-util.h"
45 static int name_owner_change_callback(sd_bus_message
*m
, void *userdata
, sd_bus_error
*ret_error
) {
46 sd_event
*e
= userdata
;
51 sd_bus_close(sd_bus_message_get_bus(m
));
57 int bus_async_unregister_and_exit(sd_event
*e
, sd_bus
*bus
, const char *name
) {
66 /* We unregister the name here and then wait for the
67 * NameOwnerChanged signal for this event to arrive before we
68 * quit. We do this in order to make sure that any queued
69 * requests are still processed before we really exit. */
71 r
= sd_bus_get_unique_name(bus
, &unique
);
76 "sender='org.freedesktop.DBus',"
78 "interface='org.freedesktop.DBus',"
79 "member='NameOwnerChanged',"
80 "path='/org/freedesktop/DBus',"
82 "arg1='", unique
, "',",
85 r
= sd_bus_add_match_async(bus
, NULL
, match
, name_owner_change_callback
, NULL
, e
);
89 r
= sd_bus_release_name_async(bus
, NULL
, name
, NULL
, NULL
);
96 int bus_event_loop_with_idle(
101 check_idle_t check_idle
,
103 bool exiting
= false;
113 r
= sd_event_get_state(e
);
116 if (r
== SD_EVENT_FINISHED
)
120 idle
= check_idle(userdata
);
124 r
= sd_event_run(e
, exiting
|| !idle
? (uint64_t) -1 : timeout
);
128 if (r
== 0 && !exiting
&& idle
) {
130 r
= sd_bus_try_close(bus
);
134 /* Fallback for dbus1 connections: we
135 * unregister the name and wait for the
136 * response to come through for it */
137 if (r
== -EOPNOTSUPP
) {
139 /* Inform the service manager that we
140 * are going down, so that it will
141 * queue all further start requests,
142 * instead of assuming we are already
144 sd_notify(false, "STOPPING=1");
146 r
= bus_async_unregister_and_exit(e
, bus
, name
);
162 r
= sd_event_get_exit_code(e
, &code
);
169 int bus_name_has_owner(sd_bus
*c
, const char *name
, sd_bus_error
*error
) {
170 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*rep
= NULL
;
171 int r
, has_owner
= 0;
176 r
= sd_bus_call_method(c
,
177 "org.freedesktop.DBus",
178 "/org/freedesktop/dbus",
179 "org.freedesktop.DBus",
188 r
= sd_bus_message_read_basic(rep
, 'b', &has_owner
);
190 return sd_bus_error_set_errno(error
, r
);
195 static int check_good_user(sd_bus_message
*m
, uid_t good_user
) {
196 _cleanup_(sd_bus_creds_unrefp
) sd_bus_creds
*creds
= NULL
;
202 if (good_user
== UID_INVALID
)
205 r
= sd_bus_query_sender_creds(m
, SD_BUS_CREDS_EUID
, &creds
);
209 /* Don't trust augmented credentials for authorization */
210 assert_return((sd_bus_creds_get_augmented_mask(creds
) & SD_BUS_CREDS_EUID
) == 0, -EPERM
);
212 r
= sd_bus_creds_get_euid(creds
, &sender_uid
);
216 return sender_uid
== good_user
;
220 sd_bus_message
*call
,
223 const char **details
,
233 /* Tests non-interactively! */
235 r
= check_good_user(call
, good_user
);
239 r
= sd_bus_query_sender_privilege(call
, capability
);
246 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*request
= NULL
;
247 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
248 int authorized
= false, challenge
= false;
249 const char *sender
, **k
, **v
;
251 sender
= sd_bus_message_get_sender(call
);
255 r
= sd_bus_message_new_method_call(
258 "org.freedesktop.PolicyKit1",
259 "/org/freedesktop/PolicyKit1/Authority",
260 "org.freedesktop.PolicyKit1.Authority",
261 "CheckAuthorization");
265 r
= sd_bus_message_append(
268 "system-bus-name", 1, "name", "s", sender
,
273 r
= sd_bus_message_open_container(request
, 'a', "{ss}");
277 STRV_FOREACH_PAIR(k
, v
, details
) {
278 r
= sd_bus_message_append(request
, "{ss}", *k
, *v
);
283 r
= sd_bus_message_close_container(request
);
287 r
= sd_bus_message_append(request
, "us", 0, NULL
);
291 r
= sd_bus_call(call
->bus
, request
, 0, e
, &reply
);
293 /* Treat no PK available as access denied */
294 if (sd_bus_error_has_name(e
, SD_BUS_ERROR_SERVICE_UNKNOWN
)) {
295 sd_bus_error_free(e
);
302 r
= sd_bus_message_enter_container(reply
, 'r', "bba{ss}");
306 r
= sd_bus_message_read(reply
, "bb", &authorized
, &challenge
);
314 *_challenge
= challenge
;
325 typedef struct AsyncPolkitQuery
{
326 sd_bus_message
*request
, *reply
;
327 sd_bus_message_handler_t callback
;
333 static void async_polkit_query_free(AsyncPolkitQuery
*q
) {
338 sd_bus_slot_unref(q
->slot
);
340 if (q
->registry
&& q
->request
)
341 hashmap_remove(q
->registry
, q
->request
);
343 sd_bus_message_unref(q
->request
);
344 sd_bus_message_unref(q
->reply
);
349 static int async_polkit_callback(sd_bus_message
*reply
, void *userdata
, sd_bus_error
*error
) {
350 _cleanup_(sd_bus_error_free
) sd_bus_error error_buffer
= SD_BUS_ERROR_NULL
;
351 AsyncPolkitQuery
*q
= userdata
;
357 q
->slot
= sd_bus_slot_unref(q
->slot
);
358 q
->reply
= sd_bus_message_ref(reply
);
360 r
= sd_bus_message_rewind(q
->request
, true);
362 r
= sd_bus_reply_method_errno(q
->request
, r
, NULL
);
366 r
= q
->callback(q
->request
, q
->userdata
, &error_buffer
);
367 r
= bus_maybe_reply_error(q
->request
, r
, &error_buffer
);
370 async_polkit_query_free(q
);
377 int bus_verify_polkit_async(
378 sd_bus_message
*call
,
381 const char **details
,
385 sd_bus_error
*error
) {
388 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*pk
= NULL
;
390 const char *sender
, **k
, **v
;
391 sd_bus_message_handler_t callback
;
401 r
= check_good_user(call
, good_user
);
406 q
= hashmap_get(*registry
, call
);
408 int authorized
, challenge
;
410 /* This is the second invocation of this function, and
411 * there's already a response from polkit, let's
415 if (sd_bus_message_is_method_error(q
->reply
, NULL
)) {
416 const sd_bus_error
*e
;
418 /* Copy error from polkit reply */
419 e
= sd_bus_message_get_error(q
->reply
);
420 sd_bus_error_copy(error
, e
);
422 /* Treat no PK available as access denied */
423 if (sd_bus_error_has_name(e
, SD_BUS_ERROR_SERVICE_UNKNOWN
))
426 return -sd_bus_error_get_errno(e
);
429 r
= sd_bus_message_enter_container(q
->reply
, 'r', "bba{ss}");
431 r
= sd_bus_message_read(q
->reply
, "bb", &authorized
, &challenge
);
440 return sd_bus_error_set(error
, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED
, "Interactive authentication required.");
446 r
= sd_bus_query_sender_privilege(call
, capability
);
453 if (sd_bus_get_current_message(call
->bus
) != call
)
456 callback
= sd_bus_get_current_handler(call
->bus
);
460 userdata
= sd_bus_get_current_userdata(call
->bus
);
462 sender
= sd_bus_message_get_sender(call
);
466 c
= sd_bus_message_get_allow_interactive_authorization(call
);
472 r
= hashmap_ensure_allocated(registry
, NULL
);
476 r
= sd_bus_message_new_method_call(
479 "org.freedesktop.PolicyKit1",
480 "/org/freedesktop/PolicyKit1/Authority",
481 "org.freedesktop.PolicyKit1.Authority",
482 "CheckAuthorization");
486 r
= sd_bus_message_append(
489 "system-bus-name", 1, "name", "s", sender
,
494 r
= sd_bus_message_open_container(pk
, 'a', "{ss}");
498 STRV_FOREACH_PAIR(k
, v
, details
) {
499 r
= sd_bus_message_append(pk
, "{ss}", *k
, *v
);
504 r
= sd_bus_message_close_container(pk
);
508 r
= sd_bus_message_append(pk
, "us", !!interactive
, NULL
);
512 q
= new0(AsyncPolkitQuery
, 1);
516 q
->request
= sd_bus_message_ref(call
);
517 q
->callback
= callback
;
518 q
->userdata
= userdata
;
520 r
= hashmap_put(*registry
, call
, q
);
522 async_polkit_query_free(q
);
526 q
->registry
= *registry
;
528 r
= sd_bus_call_async(call
->bus
, &q
->slot
, pk
, async_polkit_callback
, q
, 0);
530 async_polkit_query_free(q
);
540 void bus_verify_polkit_async_registry_free(Hashmap
*registry
) {
542 hashmap_free_with_destructor(registry
, async_polkit_query_free
);
546 int bus_check_peercred(sd_bus
*c
) {
552 fd
= sd_bus_get_fd(c
);
556 r
= getpeercred(fd
, &ucred
);
560 if (ucred
.uid
!= 0 && ucred
.uid
!= geteuid())
566 int bus_connect_system_systemd(sd_bus
**_bus
) {
567 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
573 return sd_bus_default_system(_bus
);
575 /* If we are root then let's talk directly to the system
576 * instance, instead of going via the bus */
578 r
= sd_bus_new(&bus
);
582 r
= sd_bus_set_address(bus
, "unix:path=/run/systemd/private");
586 r
= sd_bus_start(bus
);
588 return sd_bus_default_system(_bus
);
590 r
= bus_check_peercred(bus
);
594 *_bus
= TAKE_PTR(bus
);
599 int bus_connect_user_systemd(sd_bus
**_bus
) {
600 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
601 _cleanup_free_
char *ee
= NULL
;
607 e
= secure_getenv("XDG_RUNTIME_DIR");
609 return sd_bus_default_user(_bus
);
611 ee
= bus_address_escape(e
);
615 r
= sd_bus_new(&bus
);
619 bus
->address
= strjoin("unix:path=", ee
, "/systemd/private");
623 r
= sd_bus_start(bus
);
625 return sd_bus_default_user(_bus
);
627 r
= bus_check_peercred(bus
);
631 *_bus
= TAKE_PTR(bus
);
636 #define print_property(name, fmt, ...) \
639 printf(fmt "\n", __VA_ARGS__); \
641 printf("%s=" fmt "\n", name, __VA_ARGS__); \
644 int bus_print_property(const char *name
, sd_bus_message
*m
, bool value
, bool all
) {
646 const char *contents
;
652 r
= sd_bus_message_peek_type(m
, &type
, &contents
);
658 case SD_BUS_TYPE_STRING
: {
661 r
= sd_bus_message_read_basic(m
, type
, &s
);
665 if (all
|| !isempty(s
)) {
668 /* This property has a single value, so we need to take
669 * care not to print a new line, everything else is OK. */
670 good
= !strchr(s
, '\n');
671 print_property(name
, "%s", good
? s
: "[unprintable]");
677 case SD_BUS_TYPE_BOOLEAN
: {
680 r
= sd_bus_message_read_basic(m
, type
, &b
);
684 print_property(name
, "%s", yes_no(b
));
689 case SD_BUS_TYPE_UINT64
: {
692 r
= sd_bus_message_read_basic(m
, type
, &u
);
696 /* Yes, heuristics! But we can change this check
697 * should it turn out to not be sufficient */
699 if (endswith(name
, "Timestamp") ||
700 STR_IN_SET(name
, "NextElapseUSecRealtime", "LastTriggerUSec", "TimeUSec", "RTCTimeUSec")) {
701 char timestamp
[FORMAT_TIMESTAMP_MAX
];
704 t
= format_timestamp(timestamp
, sizeof(timestamp
), u
);
706 print_property(name
, "%s", strempty(t
));
708 } else if (strstr(name
, "USec")) {
709 char timespan
[FORMAT_TIMESPAN_MAX
];
711 print_property(name
, "%s", format_timespan(timespan
, sizeof(timespan
), u
, 0));
712 } else if (streq(name
, "RestrictNamespaces")) {
713 _cleanup_free_
char *s
= NULL
;
716 if ((u
& NAMESPACE_FLAGS_ALL
) == 0)
718 else if ((u
& NAMESPACE_FLAGS_ALL
) == NAMESPACE_FLAGS_ALL
)
721 r
= namespace_flags_to_string(u
, &s
);
728 print_property(name
, "%s", result
);
730 } else if (streq(name
, "MountFlags")) {
733 result
= mount_propagation_flags_to_string(u
);
737 print_property(name
, "%s", result
);
739 } else if (STR_IN_SET(name
, "CapabilityBoundingSet", "AmbientCapabilities")) {
740 _cleanup_free_
char *s
= NULL
;
742 r
= capability_set_to_string_alloc(u
, &s
);
746 print_property(name
, "%s", s
);
748 } else if ((STR_IN_SET(name
, "CPUWeight", "StartupCPUWeight", "IOWeight", "StartupIOWeight") && u
== CGROUP_WEIGHT_INVALID
) ||
749 (STR_IN_SET(name
, "CPUShares", "StartupCPUShares") && u
== CGROUP_CPU_SHARES_INVALID
) ||
750 (STR_IN_SET(name
, "BlockIOWeight", "StartupBlockIOWeight") && u
== CGROUP_BLKIO_WEIGHT_INVALID
) ||
751 (STR_IN_SET(name
, "MemoryCurrent", "TasksCurrent") && u
== (uint64_t) -1) ||
752 (endswith(name
, "NSec") && u
== (uint64_t) -1))
754 print_property(name
, "%s", "[not set]");
756 else if ((STR_IN_SET(name
, "MemoryLow", "MemoryHigh", "MemoryMax", "MemorySwapMax", "MemoryLimit") && u
== CGROUP_LIMIT_MAX
) ||
757 (STR_IN_SET(name
, "TasksMax", "DefaultTasksMax") && u
== (uint64_t) -1) ||
758 (startswith(name
, "Limit") && u
== (uint64_t) -1) ||
759 (startswith(name
, "DefaultLimit") && u
== (uint64_t) -1))
761 print_property(name
, "%s", "infinity");
763 print_property(name
, "%"PRIu64
, u
);
768 case SD_BUS_TYPE_INT64
: {
771 r
= sd_bus_message_read_basic(m
, type
, &i
);
775 print_property(name
, "%"PRIi64
, i
);
780 case SD_BUS_TYPE_UINT32
: {
783 r
= sd_bus_message_read_basic(m
, type
, &u
);
787 if (strstr(name
, "UMask") || strstr(name
, "Mode"))
788 print_property(name
, "%04o", u
);
789 else if (streq(name
, "UID")) {
790 if (u
== UID_INVALID
)
791 print_property(name
, "%s", "[not set]");
793 print_property(name
, "%"PRIu32
, u
);
794 } else if (streq(name
, "GID")) {
795 if (u
== GID_INVALID
)
796 print_property(name
, "%s", "[not set]");
798 print_property(name
, "%"PRIu32
, u
);
800 print_property(name
, "%"PRIu32
, u
);
805 case SD_BUS_TYPE_INT32
: {
808 r
= sd_bus_message_read_basic(m
, type
, &i
);
812 print_property(name
, "%"PRIi32
, i
);
816 case SD_BUS_TYPE_DOUBLE
: {
819 r
= sd_bus_message_read_basic(m
, type
, &d
);
823 print_property(name
, "%g", d
);
827 case SD_BUS_TYPE_ARRAY
:
828 if (streq(contents
, "s")) {
832 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, contents
);
836 while ((r
= sd_bus_message_read_basic(m
, SD_BUS_TYPE_STRING
, &str
)) > 0) {
842 /* This property has multiple space-separated values, so
843 * neither spaces nor newlines can be allowed in a value. */
844 good
= str
[strcspn(str
, " \n")] == '\0';
846 printf("%s%s", first
? "" : " ", good
? str
: "[unprintable]");
853 if (first
&& all
&& !value
)
858 r
= sd_bus_message_exit_container(m
);
864 } else if (streq(contents
, "y")) {
868 r
= sd_bus_message_read_array(m
, SD_BUS_TYPE_BYTE
, (const void**) &u
, &n
);
878 for (i
= 0; i
< n
; i
++)
879 printf("%02x", u
[i
]);
886 } else if (streq(contents
, "u")) {
890 r
= sd_bus_message_read_array(m
, SD_BUS_TYPE_UINT32
, (const void**) &u
, &n
);
900 for (i
= 0; i
< n
; i
++)
901 printf("%08x", u
[i
]);
915 int bus_message_print_all_properties(
917 bus_message_print_t func
,
921 Set
**found_properties
) {
927 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "{sv}");
931 while ((r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_DICT_ENTRY
, "sv")) > 0) {
933 const char *contents
;
935 r
= sd_bus_message_read_basic(m
, SD_BUS_TYPE_STRING
, &name
);
939 if (found_properties
) {
940 r
= set_ensure_allocated(found_properties
, &string_hash_ops
);
944 r
= set_put(*found_properties
, name
);
945 if (r
< 0 && r
!= EEXIST
)
949 if (!filter
|| strv_find(filter
, name
)) {
950 r
= sd_bus_message_peek_type(m
, NULL
, &contents
);
954 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_VARIANT
, contents
);
959 r
= func(name
, m
, value
, all
);
961 r
= bus_print_property(name
, m
, value
, all
);
966 printf("%s=[unprintable]\n", name
);
967 /* skip what we didn't read */
968 r
= sd_bus_message_skip(m
, contents
);
973 r
= sd_bus_message_exit_container(m
);
977 r
= sd_bus_message_skip(m
, "v");
982 r
= sd_bus_message_exit_container(m
);
989 r
= sd_bus_message_exit_container(m
);
996 int bus_print_all_properties(
1000 bus_message_print_t func
,
1004 Set
**found_properties
) {
1006 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1007 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1013 r
= sd_bus_call_method(bus
,
1016 "org.freedesktop.DBus.Properties",
1024 return bus_message_print_all_properties(reply
, func
, filter
, value
, all
, found_properties
);
1027 int bus_map_id128(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
1028 sd_id128_t
*p
= userdata
;
1033 r
= sd_bus_message_read_array(m
, SD_BUS_TYPE_BYTE
, &v
, &n
);
1040 memcpy((*p
).bytes
, v
, n
);
1047 static int map_basic(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, unsigned flags
, sd_bus_error
*error
, void *userdata
) {
1051 r
= sd_bus_message_peek_type(m
, &type
, NULL
);
1057 case SD_BUS_TYPE_STRING
: {
1058 const char **p
= userdata
;
1061 r
= sd_bus_message_read_basic(m
, type
, &s
);
1068 if (flags
& BUS_MAP_STRDUP
)
1069 return free_and_strdup((char **) userdata
, s
);
1075 case SD_BUS_TYPE_ARRAY
: {
1076 _cleanup_strv_free_
char **l
= NULL
;
1077 char ***p
= userdata
;
1079 r
= bus_message_read_strv_extend(m
, &l
);
1083 return strv_free_and_replace(*p
, l
);
1086 case SD_BUS_TYPE_BOOLEAN
: {
1089 r
= sd_bus_message_read_basic(m
, type
, &b
);
1093 if (flags
& BUS_MAP_BOOLEAN_AS_BOOL
)
1094 *(bool*) userdata
= b
;
1096 *(int*) userdata
= b
;
1101 case SD_BUS_TYPE_INT32
:
1102 case SD_BUS_TYPE_UINT32
: {
1103 uint32_t u
, *p
= userdata
;
1105 r
= sd_bus_message_read_basic(m
, type
, &u
);
1113 case SD_BUS_TYPE_INT64
:
1114 case SD_BUS_TYPE_UINT64
: {
1115 uint64_t t
, *p
= userdata
;
1117 r
= sd_bus_message_read_basic(m
, type
, &t
);
1125 case SD_BUS_TYPE_DOUBLE
: {
1126 double d
, *p
= userdata
;
1128 r
= sd_bus_message_read_basic(m
, type
, &d
);
1139 int bus_message_map_all_properties(
1141 const struct bus_properties_map
*map
,
1143 sd_bus_error
*error
,
1151 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "{sv}");
1155 while ((r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_DICT_ENTRY
, "sv")) > 0) {
1156 const struct bus_properties_map
*prop
;
1158 const char *contents
;
1162 r
= sd_bus_message_read_basic(m
, SD_BUS_TYPE_STRING
, &member
);
1166 for (i
= 0, prop
= NULL
; map
[i
].member
; i
++)
1167 if (streq(map
[i
].member
, member
)) {
1173 r
= sd_bus_message_peek_type(m
, NULL
, &contents
);
1177 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_VARIANT
, contents
);
1181 v
= (uint8_t *)userdata
+ prop
->offset
;
1183 r
= prop
->set(sd_bus_message_get_bus(m
), member
, m
, error
, v
);
1185 r
= map_basic(sd_bus_message_get_bus(m
), member
, m
, flags
, error
, v
);
1189 r
= sd_bus_message_exit_container(m
);
1193 r
= sd_bus_message_skip(m
, "v");
1198 r
= sd_bus_message_exit_container(m
);
1205 return sd_bus_message_exit_container(m
);
1208 int bus_message_map_properties_changed(
1210 const struct bus_properties_map
*map
,
1212 sd_bus_error
*error
,
1216 int r
, invalidated
, i
;
1221 r
= bus_message_map_all_properties(m
, map
, flags
, error
, userdata
);
1225 r
= sd_bus_message_enter_container(m
, SD_BUS_TYPE_ARRAY
, "s");
1230 while ((r
= sd_bus_message_read_basic(m
, SD_BUS_TYPE_STRING
, &member
)) > 0)
1231 for (i
= 0; map
[i
].member
; i
++)
1232 if (streq(map
[i
].member
, member
)) {
1239 r
= sd_bus_message_exit_container(m
);
1246 int bus_map_all_properties(
1248 const char *destination
,
1250 const struct bus_properties_map
*map
,
1252 sd_bus_error
*error
,
1253 sd_bus_message
**reply
,
1256 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1260 assert(destination
);
1263 assert(reply
|| (flags
& BUS_MAP_STRDUP
));
1265 r
= sd_bus_call_method(
1269 "org.freedesktop.DBus.Properties",
1277 r
= bus_message_map_all_properties(m
, map
, flags
, error
, userdata
);
1282 *reply
= sd_bus_message_ref(m
);
1287 int bus_connect_transport(BusTransport transport
, const char *host
, bool user
, sd_bus
**ret
) {
1288 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
1291 assert(transport
>= 0);
1292 assert(transport
< _BUS_TRANSPORT_MAX
);
1295 assert_return((transport
== BUS_TRANSPORT_LOCAL
) == !host
, -EINVAL
);
1296 assert_return(transport
== BUS_TRANSPORT_LOCAL
|| !user
, -EOPNOTSUPP
);
1298 switch (transport
) {
1300 case BUS_TRANSPORT_LOCAL
:
1302 r
= sd_bus_default_user(&bus
);
1304 if (sd_booted() <= 0) {
1305 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1306 log_error("System has not been booted with systemd as init system (PID 1). Can't operate.");
1310 r
= sd_bus_default_system(&bus
);
1314 case BUS_TRANSPORT_REMOTE
:
1315 r
= sd_bus_open_system_remote(&bus
, host
);
1318 case BUS_TRANSPORT_MACHINE
:
1319 r
= sd_bus_open_system_machine(&bus
, host
);
1323 assert_not_reached("Hmm, unknown transport type.");
1328 r
= sd_bus_set_exit_on_disconnect(bus
, true);
1332 *ret
= TAKE_PTR(bus
);
1337 int bus_connect_transport_systemd(BusTransport transport
, const char *host
, bool user
, sd_bus
**bus
) {
1340 assert(transport
>= 0);
1341 assert(transport
< _BUS_TRANSPORT_MAX
);
1344 assert_return((transport
== BUS_TRANSPORT_LOCAL
) == !host
, -EINVAL
);
1345 assert_return(transport
== BUS_TRANSPORT_LOCAL
|| !user
, -EOPNOTSUPP
);
1347 switch (transport
) {
1349 case BUS_TRANSPORT_LOCAL
:
1351 r
= bus_connect_user_systemd(bus
);
1353 if (sd_booted() <= 0) {
1354 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1355 log_error("System has not been booted with systemd as init system (PID 1). Can't operate.");
1359 r
= bus_connect_system_systemd(bus
);
1363 case BUS_TRANSPORT_REMOTE
:
1364 r
= sd_bus_open_system_remote(bus
, host
);
1367 case BUS_TRANSPORT_MACHINE
:
1368 r
= sd_bus_open_system_machine(bus
, host
);
1372 assert_not_reached("Hmm, unknown transport type.");
1378 int bus_property_get_bool(
1381 const char *interface
,
1382 const char *property
,
1383 sd_bus_message
*reply
,
1385 sd_bus_error
*error
) {
1387 int b
= *(bool*) userdata
;
1389 return sd_bus_message_append_basic(reply
, 'b', &b
);
1392 int bus_property_set_bool(
1395 const char *interface
,
1396 const char *property
,
1397 sd_bus_message
*value
,
1399 sd_bus_error
*error
) {
1403 r
= sd_bus_message_read(value
, "b", &b
);
1407 *(bool*) userdata
= b
;
1411 int bus_property_get_id128(
1414 const char *interface
,
1415 const char *property
,
1416 sd_bus_message
*reply
,
1418 sd_bus_error
*error
) {
1420 sd_id128_t
*id
= userdata
;
1422 if (sd_id128_is_null(*id
)) /* Add an empty array if the ID is zero */
1423 return sd_bus_message_append(reply
, "ay", 0);
1425 return sd_bus_message_append_array(reply
, 'y', id
->bytes
, 16);
1428 #if __SIZEOF_SIZE_T__ != 8
1429 int bus_property_get_size(
1432 const char *interface
,
1433 const char *property
,
1434 sd_bus_message
*reply
,
1436 sd_bus_error
*error
) {
1438 uint64_t sz
= *(size_t*) userdata
;
1440 return sd_bus_message_append_basic(reply
, 't', &sz
);
1444 #if __SIZEOF_LONG__ != 8
1445 int bus_property_get_long(
1448 const char *interface
,
1449 const char *property
,
1450 sd_bus_message
*reply
,
1452 sd_bus_error
*error
) {
1454 int64_t l
= *(long*) userdata
;
1456 return sd_bus_message_append_basic(reply
, 'x', &l
);
1459 int bus_property_get_ulong(
1462 const char *interface
,
1463 const char *property
,
1464 sd_bus_message
*reply
,
1466 sd_bus_error
*error
) {
1468 uint64_t ul
= *(unsigned long*) userdata
;
1470 return sd_bus_message_append_basic(reply
, 't', &ul
);
1474 int bus_log_parse_error(int r
) {
1475 return log_error_errno(r
, "Failed to parse bus message: %m");
1478 int bus_log_create_error(int r
) {
1479 return log_error_errno(r
, "Failed to create bus message: %m");
1483 * bus_path_encode_unique() - encode unique object path
1484 * @b: bus connection or NULL
1485 * @prefix: object path prefix
1486 * @sender_id: unique-name of client, or NULL
1487 * @external_id: external ID to be chosen by client, or NULL
1488 * @ret_path: storage for encoded object path pointer
1490 * Whenever we provide a bus API that allows clients to create and manage
1491 * server-side objects, we need to provide a unique name for these objects. If
1492 * we let the server choose the name, we suffer from a race condition: If a
1493 * client creates an object asynchronously, it cannot destroy that object until
1494 * it received the method reply. It cannot know the name of the new object,
1495 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
1497 * Therefore, many APIs allow the client to choose the unique name for newly
1498 * created objects. There're two problems to solve, though:
1499 * 1) Object names are usually defined via dbus object paths, which are
1500 * usually globally namespaced. Therefore, multiple clients must be able
1501 * to choose unique object names without interference.
1502 * 2) If multiple libraries share the same bus connection, they must be
1503 * able to choose unique object names without interference.
1504 * The first problem is solved easily by prefixing a name with the
1505 * unique-bus-name of a connection. The server side must enforce this and
1506 * reject any other name. The second problem is solved by providing unique
1507 * suffixes from within sd-bus.
1509 * This helper allows clients to create unique object-paths. It uses the
1510 * template '/prefix/sender_id/external_id' and returns the new path in
1511 * @ret_path (must be freed by the caller).
1512 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
1513 * NULL, this function allocates a unique suffix via @b (by requesting a new
1514 * cookie). If both @sender_id and @external_id are given, @b can be passed as
1517 * Returns: 0 on success, negative error code on failure.
1519 int bus_path_encode_unique(sd_bus
*b
, const char *prefix
, const char *sender_id
, const char *external_id
, char **ret_path
) {
1520 _cleanup_free_
char *sender_label
= NULL
, *external_label
= NULL
;
1521 char external_buf
[DECIMAL_STR_MAX(uint64_t)], *p
;
1524 assert_return(b
|| (sender_id
&& external_id
), -EINVAL
);
1525 assert_return(object_path_is_valid(prefix
), -EINVAL
);
1526 assert_return(ret_path
, -EINVAL
);
1529 r
= sd_bus_get_unique_name(b
, &sender_id
);
1535 xsprintf(external_buf
, "%"PRIu64
, ++b
->cookie
);
1536 external_id
= external_buf
;
1539 sender_label
= bus_label_escape(sender_id
);
1543 external_label
= bus_label_escape(external_id
);
1544 if (!external_label
)
1547 p
= strjoin(prefix
, "/", sender_label
, "/", external_label
);
1556 * bus_path_decode_unique() - decode unique object path
1557 * @path: object path to decode
1558 * @prefix: object path prefix
1559 * @ret_sender: output parameter for sender-id label
1560 * @ret_external: output parameter for external-id label
1562 * This does the reverse of bus_path_encode_unique() (see its description for
1563 * details). Both trailing labels, sender-id and external-id, are unescaped and
1564 * returned in the given output parameters (the caller must free them).
1566 * Note that this function returns 0 if the path does not match the template
1567 * (see bus_path_encode_unique()), 1 if it matched.
1569 * Returns: Negative error code on failure, 0 if the given object path does not
1570 * match the template (return parameters are set to NULL), 1 if it was
1571 * parsed successfully (return parameters contain allocated labels).
1573 int bus_path_decode_unique(const char *path
, const char *prefix
, char **ret_sender
, char **ret_external
) {
1575 char *sender
, *external
;
1577 assert(object_path_is_valid(path
));
1578 assert(object_path_is_valid(prefix
));
1580 assert(ret_external
);
1582 p
= object_path_startswith(path
, prefix
);
1585 *ret_external
= NULL
;
1592 *ret_external
= NULL
;
1596 sender
= bus_label_unescape_n(p
, q
- p
);
1597 external
= bus_label_unescape(q
+ 1);
1598 if (!sender
|| !external
) {
1604 *ret_sender
= sender
;
1605 *ret_external
= external
;
1609 int bus_property_get_rlimit(
1612 const char *interface
,
1613 const char *property
,
1614 sd_bus_message
*reply
,
1616 sd_bus_error
*error
) {
1618 const char *is_soft
;
1627 is_soft
= endswith(property
, "Soft");
1629 rl
= *(struct rlimit
**) userdata
;
1631 x
= is_soft
? rl
->rlim_cur
: rl
->rlim_max
;
1633 struct rlimit buf
= {};
1637 /* Chop off "Soft" suffix */
1638 s
= is_soft
? strndupa(property
, is_soft
- property
) : property
;
1640 /* Skip over any prefix, such as "Default" */
1641 assert_se(p
= strstr(s
, "Limit"));
1643 z
= rlimit_from_string(p
+ 5);
1646 (void) getrlimit(z
, &buf
);
1647 x
= is_soft
? buf
.rlim_cur
: buf
.rlim_max
;
1650 /* rlim_t might have different sizes, let's map RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on all
1652 u
= x
== RLIM_INFINITY
? (uint64_t) -1 : (uint64_t) x
;
1654 return sd_bus_message_append(reply
, "t", u
);
1657 int bus_track_add_name_many(sd_bus_track
*t
, char **l
) {
1663 /* Continues adding after failure, and returns the first failure. */
1665 STRV_FOREACH(i
, l
) {
1668 k
= sd_bus_track_add_name(t
, *i
);
1669 if (k
< 0 && r
>= 0)
1676 int bus_open_system_watch_bind_with_description(sd_bus
**ret
, const char *description
) {
1677 _cleanup_(sd_bus_unrefp
) sd_bus
*bus
= NULL
;
1683 /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal turned on. */
1685 r
= sd_bus_new(&bus
);
1690 r
= sd_bus_set_description(bus
, description
);
1695 e
= secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1697 e
= DEFAULT_SYSTEM_BUS_ADDRESS
;
1699 r
= sd_bus_set_address(bus
, e
);
1703 r
= sd_bus_set_bus_client(bus
, true);
1707 r
= sd_bus_set_trusted(bus
, true);
1711 r
= sd_bus_negotiate_creds(bus
, true, SD_BUS_CREDS_UID
|SD_BUS_CREDS_EUID
|SD_BUS_CREDS_EFFECTIVE_CAPS
);
1715 r
= sd_bus_set_watch_bind(bus
, true);
1719 r
= sd_bus_set_connected_signal(bus
, true);
1723 r
= sd_bus_start(bus
);
1727 *ret
= TAKE_PTR(bus
);
1732 struct request_name_data
{
1740 static void request_name_destroy_callback(void *userdata
) {
1741 struct request_name_data
*data
= userdata
;
1744 assert(data
->n_ref
> 0);
1746 log_info("%s n_ref=%u", __func__
, data
->n_ref
);
1749 if (data
->n_ref
== 0)
1753 static int reload_dbus_handler(sd_bus_message
*m
, void *userdata
, sd_bus_error
*ret_error
) {
1754 struct request_name_data
*data
= userdata
;
1755 const sd_bus_error
*e
;
1760 assert(data
->n_ref
> 0);
1762 e
= sd_bus_message_get_error(m
);
1764 log_error_errno(sd_bus_error_get_errno(e
), "Failed to reload DBus configuration: %s", e
->message
);
1768 /* Here, use the default request name handler to avoid an infinite loop of reloading and requesting. */
1769 r
= sd_bus_request_name_async(sd_bus_message_get_bus(m
), NULL
, data
->name
, data
->flags
, NULL
, data
->userdata
);
1771 log_error_errno(r
, "Failed to request name: %m");
1776 static int request_name_handler_may_reload_dbus(sd_bus_message
*m
, void *userdata
, sd_bus_error
*ret_error
) {
1777 struct request_name_data
*data
= userdata
;
1784 if (sd_bus_message_is_method_error(m
, NULL
)) {
1785 const sd_bus_error
*e
= sd_bus_message_get_error(m
);
1786 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot
= NULL
;
1788 if (!sd_bus_error_has_name(e
, SD_BUS_ERROR_ACCESS_DENIED
)) {
1789 log_debug_errno(sd_bus_error_get_errno(e
),
1790 "Unable to request name, failing connection: %s",
1793 bus_enter_closing(sd_bus_message_get_bus(m
));
1797 log_debug_errno(sd_bus_error_get_errno(e
),
1798 "Unable to request name, will retry after reloading DBus configuration: %s",
1801 /* If systemd-timesyncd.service enables DynamicUser= and dbus.service
1802 * started before the dynamic user is realized, then the DBus policy
1803 * about timesyncd has not been enabled yet. So, let's try to reload
1804 * DBus configuration, and after that request the name again. Note that it
1805 * seems that no privileges are necessary to call the following method. */
1807 r
= sd_bus_call_method_async(
1808 sd_bus_message_get_bus(m
),
1810 "org.freedesktop.DBus",
1811 "/org/freedesktop/DBus",
1812 "org.freedesktop.DBus",
1814 reload_dbus_handler
,
1817 log_error_errno(r
, "Failed to reload DBus configuration: %m");
1818 bus_enter_closing(sd_bus_message_get_bus(m
));
1823 assert_se(sd_bus_slot_set_destroy_callback(slot
, request_name_destroy_callback
) >= 0);
1825 r
= sd_bus_slot_set_floating(slot
, true);
1832 r
= sd_bus_message_read(m
, "u", &ret
);
1838 case BUS_NAME_ALREADY_OWNER
:
1839 log_debug("Already owner of requested service name, ignoring.");
1842 case BUS_NAME_IN_QUEUE
:
1843 log_debug("In queue for requested service name.");
1846 case BUS_NAME_PRIMARY_OWNER
:
1847 log_debug("Successfully acquired requested service name.");
1850 case BUS_NAME_EXISTS
:
1851 log_debug("Requested service name already owned, failing connection.");
1852 bus_enter_closing(sd_bus_message_get_bus(m
));
1856 log_debug("Unexpected response from RequestName(), failing connection.");
1857 bus_enter_closing(sd_bus_message_get_bus(m
));
1861 int bus_request_name_async_may_reload_dbus(sd_bus
*bus
, sd_bus_slot
**ret_slot
, const char *name
, uint64_t flags
, void *userdata
) {
1862 _cleanup_free_
struct request_name_data
*data
= NULL
;
1863 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*slot
= NULL
;
1866 data
= new(struct request_name_data
, 1);
1870 *data
= (struct request_name_data
) {
1874 .userdata
= userdata
,
1877 r
= sd_bus_request_name_async(bus
, &slot
, name
, flags
, request_name_handler_may_reload_dbus
, data
);
1881 assert_se(sd_bus_slot_set_destroy_callback(slot
, request_name_destroy_callback
) >= 0);
1885 *ret_slot
= TAKE_PTR(slot
);
1887 r
= sd_bus_slot_set_floating(slot
, true);
1895 int bus_reply_pair_array(sd_bus_message
*m
, char **l
) {
1896 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1902 /* Reply to the specified message with a message containing a dictionary put together from the specified
1905 r
= sd_bus_message_new_method_return(m
, &reply
);
1909 r
= sd_bus_message_open_container(reply
, 'a', "{ss}");
1913 STRV_FOREACH_PAIR(k
, v
, l
) {
1914 r
= sd_bus_message_append(reply
, "{ss}", *k
, *v
);
1919 r
= sd_bus_message_close_container(reply
);
1923 return sd_bus_send(NULL
, reply
, NULL
);