1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
8 #include <sys/resource.h>
9 #include <sys/socket.h>
13 #include "sd-daemon.h"
17 #include "bus-common-errors.h"
18 #include "bus-internal.h"
19 #include "bus-label.h"
21 #include "capsule-util.h"
23 #include "daemon-util.h"
24 #include "data-fd-util.h"
26 #include "format-util.h"
27 #include "memstream-util.h"
28 #include "path-util.h"
29 #include "socket-util.h"
30 #include "stdio-util.h"
31 #include "uid-classification.h"
33 static int name_owner_change_callback(sd_bus_message
*m
, void *userdata
, sd_bus_error
*ret_error
) {
34 sd_event
*e
= ASSERT_PTR(userdata
);
38 sd_bus_close(sd_bus_message_get_bus(m
));
44 int bus_log_address_error(int r
, BusTransport transport
) {
45 bool hint
= transport
== BUS_TRANSPORT_LOCAL
&& r
== -ENOMEDIUM
;
47 return log_error_errno(r
,
48 hint
? "Failed to set bus address: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined (consider using --machine=<user>@.host --user to connect to bus of other user)" :
49 "Failed to set bus address: %m");
52 int bus_log_connect_error(int r
, BusTransport transport
) {
53 bool hint_vars
= transport
== BUS_TRANSPORT_LOCAL
&& r
== -ENOMEDIUM
,
54 hint_addr
= transport
== BUS_TRANSPORT_LOCAL
&& ERRNO_IS_PRIVILEGE(r
);
56 return log_error_errno(r
,
57 r
== hint_vars
? "Failed to connect to bus: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined (consider using --machine=<user>@.host --user to connect to bus of other user)" :
58 r
== hint_addr
? "Failed to connect to bus: Operation not permitted (consider using --machine=<user>@.host --user to connect to bus of other user)" :
59 "Failed to connect to bus: %m");
62 int bus_async_unregister_and_exit(sd_event
*e
, sd_bus
*bus
, const char *name
) {
71 /* We unregister the name here and then wait for the
72 * NameOwnerChanged signal for this event to arrive before we
73 * quit. We do this in order to make sure that any queued
74 * requests are still processed before we really exit. */
76 r
= sd_bus_get_unique_name(bus
, &unique
);
81 "sender='org.freedesktop.DBus',"
83 "interface='org.freedesktop.DBus',"
84 "member='NameOwnerChanged',"
85 "path='/org/freedesktop/DBus',"
87 "arg1='", unique
, "',",
90 r
= sd_bus_add_match_async(bus
, NULL
, match
, name_owner_change_callback
, NULL
, e
);
94 r
= sd_bus_release_name_async(bus
, NULL
, name
, NULL
, NULL
);
101 int bus_event_loop_with_idle(
106 check_idle_t check_idle
,
109 bool exiting
= false;
119 r
= sd_event_get_state(e
);
122 if (r
== SD_EVENT_FINISHED
)
126 idle
= check_idle(userdata
);
130 r
= sd_event_run(e
, exiting
|| !idle
? UINT64_MAX
: timeout
);
134 if (r
== 0 && !exiting
&& idle
) {
135 /* Inform the service manager that we are going down, so that it will queue all
136 * further start requests, instead of assuming we are still running. */
137 (void) sd_notify(false, NOTIFY_STOPPING
);
139 r
= bus_async_unregister_and_exit(e
, bus
, name
);
147 r
= sd_event_get_exit_code(e
, &code
);
154 int bus_name_has_owner(sd_bus
*c
, const char *name
, sd_bus_error
*error
) {
155 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*rep
= NULL
;
156 int r
, has_owner
= 0;
161 r
= sd_bus_call_method(c
,
162 "org.freedesktop.DBus",
163 "/org/freedesktop/dbus",
164 "org.freedesktop.DBus",
173 r
= sd_bus_message_read_basic(rep
, 'b', &has_owner
);
175 return sd_bus_error_set_errno(error
, r
);
180 bool bus_error_is_unknown_service(const sd_bus_error
*error
) {
181 return sd_bus_error_has_names(error
,
182 SD_BUS_ERROR_SERVICE_UNKNOWN
,
183 SD_BUS_ERROR_NAME_HAS_NO_OWNER
,
184 BUS_ERROR_NO_SUCH_UNIT
);
187 int bus_check_peercred(sd_bus
*c
) {
193 fd
= sd_bus_get_fd(c
);
197 r
= getpeercred(fd
, &ucred
);
201 if (ucred
.uid
!= 0 && ucred
.uid
!= geteuid())
207 int bus_connect_system_systemd(sd_bus
**ret_bus
) {
208 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
214 return sd_bus_default_system(ret_bus
);
216 /* If we are root then let's talk directly to the system
217 * instance, instead of going via the bus */
219 r
= sd_bus_new(&bus
);
223 r
= sd_bus_set_address(bus
, "unix:path=/run/systemd/private");
227 r
= sd_bus_start(bus
);
229 return sd_bus_default_system(ret_bus
);
231 r
= bus_check_peercred(bus
);
235 *ret_bus
= TAKE_PTR(bus
);
239 int bus_connect_user_systemd(sd_bus
**ret_bus
) {
240 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
241 _cleanup_free_
char *ee
= NULL
;
247 e
= secure_getenv("XDG_RUNTIME_DIR");
249 return sd_bus_default_user(ret_bus
);
251 ee
= bus_address_escape(e
);
255 r
= sd_bus_new(&bus
);
259 bus
->address
= strjoin("unix:path=", ee
, "/systemd/private");
263 r
= sd_bus_start(bus
);
265 return sd_bus_default_user(ret_bus
);
267 r
= bus_check_peercred(bus
);
271 *ret_bus
= TAKE_PTR(bus
);
275 static int pin_capsule_socket(const char *capsule
, const char *suffix
, uid_t
*ret_uid
, gid_t
*ret_gid
) {
276 _cleanup_close_
int inode_fd
= -EBADF
;
277 _cleanup_free_
char *p
= NULL
;
284 p
= path_join("/run/capsules", capsule
, suffix
);
288 /* We enter territory owned by the user, hence let's be paranoid about symlinks and ownership */
289 r
= chase(p
, /* root= */ NULL
, CHASE_SAFE
|CHASE_PROHIBIT_SYMLINKS
, /* ret_path= */ NULL
, &inode_fd
);
293 if (fstat(inode_fd
, &st
) < 0)
296 /* Paranoid safety check */
297 if (uid_is_system(st
.st_uid
) || gid_is_system(st
.st_gid
))
300 *ret_uid
= st
.st_uid
;
301 *ret_gid
= st
.st_gid
;
303 return TAKE_FD(inode_fd
);
306 int bus_connect_capsule_systemd(const char *capsule
, sd_bus
**ret_bus
) {
307 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
308 _cleanup_close_
int inode_fd
= -EBADF
;
309 _cleanup_free_
char *pp
= NULL
;
317 r
= capsule_name_is_valid(capsule
);
323 /* Connects to a capsule's user bus. We need to do so under the capsule's UID/GID, otherwise the
324 * the service manager might refuse our connection. Hence fake it. */
326 inode_fd
= pin_capsule_socket(capsule
, "systemd/private", &uid
, &gid
);
330 pp
= bus_address_escape(FORMAT_PROC_FD_PATH(inode_fd
));
334 r
= sd_bus_new(&bus
);
338 if (asprintf(&bus
->address
, "unix:path=%s,uid=" UID_FMT
",gid=" GID_FMT
, pp
, uid
, gid
) < 0)
341 r
= sd_bus_start(bus
);
345 *ret_bus
= TAKE_PTR(bus
);
349 int bus_set_address_capsule_bus(sd_bus
*bus
, const char *capsule
, int *ret_pin_fd
) {
350 _cleanup_free_
char *pp
= NULL
;
351 _cleanup_close_
int inode_fd
= -EBADF
;
360 r
= capsule_name_is_valid(capsule
);
366 inode_fd
= pin_capsule_socket(capsule
, "bus", &uid
, &gid
);
370 pp
= bus_address_escape(FORMAT_PROC_FD_PATH(inode_fd
));
374 if (asprintf(&bus
->address
, "unix:path=%s,uid=" UID_FMT
",gid=" GID_FMT
, pp
, uid
, gid
) < 0)
377 *ret_pin_fd
= TAKE_FD(inode_fd
); /* This fd must be kept pinned until the connection has been established */
381 int bus_connect_capsule_bus(const char *capsule
, sd_bus
**ret_bus
) {
382 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
383 _cleanup_close_
int inode_fd
= -EBADF
;
389 r
= sd_bus_new(&bus
);
393 r
= bus_set_address_capsule_bus(bus
, capsule
, &inode_fd
);
397 r
= sd_bus_set_bus_client(bus
, true);
401 r
= sd_bus_start(bus
);
405 *ret_bus
= TAKE_PTR(bus
);
409 int bus_connect_transport(
410 BusTransport transport
,
412 RuntimeScope runtime_scope
,
415 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
418 assert(transport
>= 0);
419 assert(transport
< _BUS_TRANSPORT_MAX
);
424 case BUS_TRANSPORT_LOCAL
:
425 assert_return(!host
, -EINVAL
);
427 switch (runtime_scope
) {
429 case RUNTIME_SCOPE_USER
:
430 r
= sd_bus_default_user(&bus
);
433 case RUNTIME_SCOPE_SYSTEM
:
434 if (sd_booted() <= 0)
435 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
436 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
437 "System has not been booted with systemd as init system (PID 1). Can't operate.");
438 r
= sd_bus_default_system(&bus
);
442 assert_not_reached();
446 case BUS_TRANSPORT_REMOTE
:
447 assert_return(runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
449 r
= sd_bus_open_system_remote(&bus
, host
);
452 case BUS_TRANSPORT_MACHINE
:
453 switch (runtime_scope
) {
455 case RUNTIME_SCOPE_USER
:
456 r
= sd_bus_open_user_machine(&bus
, host
);
459 case RUNTIME_SCOPE_SYSTEM
:
460 r
= sd_bus_open_system_machine(&bus
, host
);
464 assert_not_reached();
469 case BUS_TRANSPORT_CAPSULE
:
470 assert_return(runtime_scope
== RUNTIME_SCOPE_USER
, -EINVAL
);
472 r
= bus_connect_capsule_bus(host
, &bus
);
476 assert_not_reached();
481 r
= sd_bus_set_exit_on_disconnect(bus
, true);
485 *ret
= TAKE_PTR(bus
);
489 int bus_connect_transport_systemd(
490 BusTransport transport
,
492 RuntimeScope runtime_scope
,
495 assert(transport
>= 0);
496 assert(transport
< _BUS_TRANSPORT_MAX
);
501 case BUS_TRANSPORT_LOCAL
:
502 assert_return(!host
, -EINVAL
);
504 switch (runtime_scope
) {
506 case RUNTIME_SCOPE_USER
:
507 return bus_connect_user_systemd(ret_bus
);
509 case RUNTIME_SCOPE_SYSTEM
:
510 if (sd_booted() <= 0)
511 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
512 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
513 "System has not been booted with systemd as init system (PID 1). Can't operate.");
514 return bus_connect_system_systemd(ret_bus
);
517 assert_not_reached();
522 case BUS_TRANSPORT_REMOTE
:
523 assert_return(runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
524 return sd_bus_open_system_remote(ret_bus
, host
);
526 case BUS_TRANSPORT_MACHINE
:
527 assert_return(runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
528 return sd_bus_open_system_machine(ret_bus
, host
);
530 case BUS_TRANSPORT_CAPSULE
:
531 assert_return(runtime_scope
== RUNTIME_SCOPE_USER
, -EINVAL
);
532 return bus_connect_capsule_systemd(host
, ret_bus
);
535 assert_not_reached();
540 * bus_path_encode_unique() - encode unique object path
541 * @b: bus connection or NULL
542 * @prefix: object path prefix
543 * @sender_id: unique-name of client, or NULL
544 * @external_id: external ID to be chosen by client, or NULL
545 * @ret_path: storage for encoded object path pointer
547 * Whenever we provide a bus API that allows clients to create and manage
548 * server-side objects, we need to provide a unique name for these objects. If
549 * we let the server choose the name, we suffer from a race condition: If a
550 * client creates an object asynchronously, it cannot destroy that object until
551 * it received the method reply. It cannot know the name of the new object,
552 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
554 * Therefore, many APIs allow the client to choose the unique name for newly
555 * created objects. There're two problems to solve, though:
556 * 1) Object names are usually defined via dbus object paths, which are
557 * usually globally namespaced. Therefore, multiple clients must be able
558 * to choose unique object names without interference.
559 * 2) If multiple libraries share the same bus connection, they must be
560 * able to choose unique object names without interference.
561 * The first problem is solved easily by prefixing a name with the
562 * unique-bus-name of a connection. The server side must enforce this and
563 * reject any other name. The second problem is solved by providing unique
564 * suffixes from within sd-bus.
566 * This helper allows clients to create unique object-paths. It uses the
567 * template '/prefix/sender_id/external_id' and returns the new path in
568 * @ret_path (must be freed by the caller).
569 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
570 * NULL, this function allocates a unique suffix via @b (by requesting a new
571 * cookie). If both @sender_id and @external_id are given, @b can be passed as
574 * Returns: 0 on success, negative error code on failure.
576 int bus_path_encode_unique(sd_bus
*b
, const char *prefix
, const char *sender_id
, const char *external_id
, char **ret_path
) {
577 _cleanup_free_
char *sender_label
= NULL
, *external_label
= NULL
;
578 char external_buf
[DECIMAL_STR_MAX(uint64_t)], *p
;
581 assert_return(b
|| (sender_id
&& external_id
), -EINVAL
);
582 assert_return(sd_bus_object_path_is_valid(prefix
), -EINVAL
);
583 assert_return(ret_path
, -EINVAL
);
586 r
= sd_bus_get_unique_name(b
, &sender_id
);
592 xsprintf(external_buf
, "%"PRIu64
, ++b
->cookie
);
593 external_id
= external_buf
;
596 sender_label
= bus_label_escape(sender_id
);
600 external_label
= bus_label_escape(external_id
);
604 p
= path_join(prefix
, sender_label
, external_label
);
613 * bus_path_decode_unique() - decode unique object path
614 * @path: object path to decode
615 * @prefix: object path prefix
616 * @ret_sender: output parameter for sender-id label
617 * @ret_external: output parameter for external-id label
619 * This does the reverse of bus_path_encode_unique() (see its description for
620 * details). Both trailing labels, sender-id and external-id, are unescaped and
621 * returned in the given output parameters (the caller must free them).
623 * Note that this function returns 0 if the path does not match the template
624 * (see bus_path_encode_unique()), 1 if it matched.
626 * Returns: Negative error code on failure, 0 if the given object path does not
627 * match the template (return parameters are set to NULL), 1 if it was
628 * parsed successfully (return parameters contain allocated labels).
630 int bus_path_decode_unique(const char *path
, const char *prefix
, char **ret_sender
, char **ret_external
) {
632 char *sender
, *external
;
634 assert(sd_bus_object_path_is_valid(path
));
635 assert(sd_bus_object_path_is_valid(prefix
));
637 assert(ret_external
);
639 p
= object_path_startswith(path
, prefix
);
642 *ret_external
= NULL
;
649 *ret_external
= NULL
;
653 sender
= bus_label_unescape_n(p
, q
- p
);
654 external
= bus_label_unescape(q
+ 1);
655 if (!sender
|| !external
) {
661 *ret_sender
= sender
;
662 *ret_external
= external
;
666 int bus_track_add_name_many(sd_bus_track
*t
, char **l
) {
671 /* Continues adding after failure, and returns the first failure. */
674 RET_GATHER(r
, sd_bus_track_add_name(t
, *i
));
678 int bus_open_system_watch_bind_with_description(sd_bus
**ret
, const char *description
) {
679 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
685 /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal
688 r
= sd_bus_new(&bus
);
693 r
= sd_bus_set_description(bus
, description
);
698 e
= secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
700 e
= DEFAULT_SYSTEM_BUS_ADDRESS
;
702 r
= sd_bus_set_address(bus
, e
);
706 r
= sd_bus_set_bus_client(bus
, true);
710 r
= sd_bus_negotiate_creds(bus
, true, SD_BUS_CREDS_UID
|SD_BUS_CREDS_EUID
|SD_BUS_CREDS_EFFECTIVE_CAPS
);
714 r
= sd_bus_set_watch_bind(bus
, true);
718 r
= sd_bus_set_connected_signal(bus
, true);
722 r
= sd_bus_start(bus
);
726 *ret
= TAKE_PTR(bus
);
731 int bus_reply_pair_array(sd_bus_message
*m
, char **l
) {
732 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
737 /* Reply to the specified message with a message containing a dictionary put together from the
740 r
= sd_bus_message_new_method_return(m
, &reply
);
744 r
= sd_bus_message_open_container(reply
, 'a', "{ss}");
748 STRV_FOREACH_PAIR(k
, v
, l
) {
749 r
= sd_bus_message_append(reply
, "{ss}", *k
, *v
);
754 r
= sd_bus_message_close_container(reply
);
758 return sd_bus_send(NULL
, reply
, NULL
);
761 static int method_dump_memory_state_by_fd(sd_bus_message
*message
, void *userdata
, sd_bus_error
*ret_error
) {
762 _cleanup_(memstream_done
) MemStream m
= {};
763 _cleanup_free_
char *dump
= NULL
;
764 _cleanup_close_
int fd
= -EBADF
;
771 f
= memstream_init(&m
);
775 r
= RET_NERRNO(malloc_info(/* options= */ 0, f
));
779 r
= memstream_finalize(&m
, &dump
, &dump_size
);
783 fd
= acquire_data_fd_full(dump
, dump_size
, /* flags = */ 0);
787 r
= sd_bus_reply_method_return(message
, "h", fd
);
791 return 1; /* Stop further processing */
794 /* The default install callback will fail and disconnect the bus if it cannot register the match, but this
795 * is only a debug method, we definitely don't want to fail in case there's some permission issue. */
796 static int dummy_install_callback(sd_bus_message
*message
, void *userdata
, sd_bus_error
*ret_error
) {
800 int bus_register_malloc_status(sd_bus
*bus
, const char *destination
) {
805 assert(!isempty(destination
));
807 match
= strjoina("type='method_call',"
808 "interface='org.freedesktop.MemoryAllocation1',"
809 "path='/org/freedesktop/MemoryAllocation1',"
810 "destination='", destination
, "',",
811 "member='GetMallocInfo'");
813 r
= sd_bus_add_match_async(bus
, NULL
, match
, method_dump_memory_state_by_fd
, dummy_install_callback
, NULL
);
815 return log_debug_errno(r
, "Failed to subscribe to GetMallocInfo() calls on MemoryAllocation1 interface: %m");
820 static void bus_message_unref_wrapper(void *m
) {
821 sd_bus_message_unref(m
);
824 const struct hash_ops bus_message_hash_ops
= {
825 .hash
= trivial_hash_func
,
826 .compare
= trivial_compare_func
,
827 .free_value
= bus_message_unref_wrapper
,
830 int bus_message_append_string_set(sd_bus_message
*m
, Set
*set
) {
836 r
= sd_bus_message_open_container(m
, 'a', "s");
840 SET_FOREACH(s
, set
) {
841 r
= sd_bus_message_append(m
, "s", s
);
846 return sd_bus_message_close_container(m
);
849 int bus_property_get_string_set(
852 const char *interface
,
853 const char *property
,
854 sd_bus_message
*reply
,
856 sd_bus_error
*error
) {
858 Set
**s
= ASSERT_PTR(userdata
);
864 return bus_message_append_string_set(reply
, *s
);
867 int bus_creds_get_pidref(
878 r
= sd_bus_creds_get_pid(c
, &pid
);
882 r
= sd_bus_creds_get_pidfd_dup(c
, &pidfd
);
883 if (r
< 0 && r
!= -ENODATA
)
894 int bus_query_sender_pidref(
898 _cleanup_(sd_bus_creds_unrefp
) sd_bus_creds
*creds
= NULL
;
904 r
= sd_bus_query_sender_creds(m
, SD_BUS_CREDS_PID
|SD_BUS_CREDS_PIDFD
, &creds
);
908 return bus_creds_get_pidref(creds
, ret
);
911 int bus_message_read_id128(sd_bus_message
*m
, sd_id128_t
*ret
) {
918 r
= sd_bus_message_read_array(m
, 'y', &a
, &sz
);
925 *ret
= SD_ID128_NULL
;
928 case sizeof(sd_id128_t
):