1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
6 #include <sys/socket.h>
11 #include "sd-daemon.h"
15 #include "alloc-util.h"
16 #include "bus-common-errors.h"
17 #include "bus-internal.h"
18 #include "bus-label.h"
20 #include "capsule-util.h"
22 #include "daemon-util.h"
24 #include "errno-util.h"
26 #include "format-util.h"
28 #include "memfd-util.h"
29 #include "memstream-util.h"
30 #include "path-util.h"
32 #include "socket-util.h"
33 #include "stdio-util.h"
34 #include "string-table.h"
35 #include "string-util.h"
37 #include "time-util.h"
38 #include "uid-classification.h"
40 static int name_owner_change_callback(sd_bus_message
*m
, void *userdata
, sd_bus_error
*reterr_error
) {
41 sd_event
*e
= ASSERT_PTR(userdata
);
45 sd_bus_close(sd_bus_message_get_bus(m
));
51 int bus_log_address_error(int r
, BusTransport transport
) {
52 bool hint
= transport
== BUS_TRANSPORT_LOCAL
&& r
== -ENOMEDIUM
;
54 return log_error_errno(r
,
55 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)" :
56 "Failed to set bus address: %m");
59 int bus_log_connect_full(int log_level
, int r
, BusTransport transport
, RuntimeScope scope
) {
60 bool hint_vars
= transport
== BUS_TRANSPORT_LOCAL
&& r
== -ENOMEDIUM
,
61 hint_addr
= transport
== BUS_TRANSPORT_LOCAL
&& ERRNO_IS_PRIVILEGE(r
);
63 return log_full_errno(log_level
, r
,
64 hint_vars
? "Failed to connect to %s scope bus via %s transport: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined (consider using --machine=<user>@.host --user to connect to bus of other user)" :
65 hint_addr
? "Failed to connect to %s scope bus via %s transport: Operation not permitted (consider using --machine=<user>@.host --user to connect to bus of other user)" :
66 "Failed to connect to %s scope bus via %s transport: %m", runtime_scope_to_string(scope
), bus_transport_to_string(transport
));
69 int bus_log_connect_error(int r
, BusTransport transport
, RuntimeScope scope
) {
70 return bus_log_connect_full(LOG_ERR
, r
, transport
, scope
);
73 int bus_async_unregister_and_exit(sd_event
*e
, sd_bus
*bus
, const char *name
) {
82 /* We unregister the name here and then wait for the
83 * NameOwnerChanged signal for this event to arrive before we
84 * quit. We do this in order to make sure that any queued
85 * requests are still processed before we really exit. */
87 r
= sd_bus_get_unique_name(bus
, &unique
);
92 "sender='org.freedesktop.DBus',"
94 "interface='org.freedesktop.DBus',"
95 "member='NameOwnerChanged',"
96 "path='/org/freedesktop/DBus',"
98 "arg1='", unique
, "',",
101 r
= sd_bus_add_match_async(bus
, NULL
, match
, name_owner_change_callback
, NULL
, e
);
105 r
= sd_bus_release_name_async(bus
, NULL
, name
, NULL
, NULL
);
112 static bool idle_allowed(void) {
113 static int allowed
= -1;
118 allowed
= secure_getenv_bool("SYSTEMD_EXIT_ON_IDLE");
119 if (allowed
< 0 && allowed
!= -ENXIO
)
120 log_debug_errno(allowed
, "Failed to parse $SYSTEMD_EXIT_ON_IDLE, ignoring: %m");
125 int bus_event_loop_with_idle(
130 check_idle_t check_idle
,
133 bool exiting
= false;
143 r
= sd_event_get_state(e
);
146 if (r
== SD_EVENT_FINISHED
)
149 if (!idle_allowed() || sd_bus_pending_method_calls(bus
) > 0)
152 idle
= check_idle(userdata
);
156 r
= sd_event_run(e
, exiting
|| !idle
? UINT64_MAX
: timeout
);
160 if (r
== 0 && !exiting
&& idle
) {
161 log_debug("Idle for %s, exiting.", FORMAT_TIMESPAN(timeout
, 1));
163 /* Inform the service manager that we are going down, so that it will queue all
164 * further start requests, instead of assuming we are still running. */
165 (void) sd_notify(false, NOTIFY_STOPPING_MESSAGE
);
167 r
= bus_async_unregister_and_exit(e
, bus
, name
);
175 r
= sd_event_get_exit_code(e
, &code
);
182 int bus_name_has_owner(sd_bus
*bus
, const char *name
, sd_bus_error
*reterr_error
) {
183 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*rep
= NULL
;
184 int r
, has_owner
= 0;
189 r
= sd_bus_call_method(bus
,
190 "org.freedesktop.DBus",
191 "/org/freedesktop/dbus",
192 "org.freedesktop.DBus",
201 r
= sd_bus_message_read_basic(rep
, 'b', &has_owner
);
203 return sd_bus_error_set_errno(reterr_error
, r
);
208 bool bus_error_is_unknown_service(const sd_bus_error
*error
) {
209 return sd_bus_error_has_names(error
,
210 SD_BUS_ERROR_SERVICE_UNKNOWN
,
211 SD_BUS_ERROR_NAME_HAS_NO_OWNER
,
212 BUS_ERROR_NO_SUCH_UNIT
);
215 bool bus_error_is_connection(const sd_bus_error
*error
) {
216 return sd_bus_error_has_names(error
,
217 SD_BUS_ERROR_NO_REPLY
,
218 SD_BUS_ERROR_DISCONNECTED
,
219 SD_BUS_ERROR_TIMED_OUT
);
222 int bus_check_peercred(sd_bus
*bus
) {
228 fd
= sd_bus_get_fd(bus
);
232 r
= getpeercred(fd
, &ucred
);
236 if (ucred
.uid
!= 0 && ucred
.uid
!= geteuid())
242 int bus_connect_system_systemd(sd_bus
**ret
) {
243 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
248 r
= sd_bus_new(&bus
);
252 r
= sd_bus_set_address(bus
, "unix:path=/run/systemd/private");
256 r
= sd_bus_start(bus
);
260 r
= bus_check_peercred(bus
);
264 *ret
= TAKE_PTR(bus
);
268 int bus_connect_user_systemd(sd_bus
**ret
) {
269 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
270 _cleanup_free_
char *ee
= NULL
;
276 e
= secure_getenv("XDG_RUNTIME_DIR");
280 ee
= bus_address_escape(e
);
284 r
= sd_bus_new(&bus
);
288 bus
->address
= strjoin("unix:path=", ee
, "/systemd/private");
292 r
= sd_bus_start(bus
);
296 r
= bus_check_peercred(bus
);
300 *ret
= TAKE_PTR(bus
);
304 static int pin_capsule_socket(const char *capsule
, const char *suffix
, uid_t
*ret_uid
, gid_t
*ret_gid
) {
305 _cleanup_close_
int inode_fd
= -EBADF
;
306 _cleanup_free_
char *p
= NULL
;
315 p
= path_join("/run/capsules", capsule
, suffix
);
319 /* We enter territory owned by the user, hence let's be paranoid about symlinks and ownership */
320 r
= chase(p
, /* root= */ NULL
, CHASE_SAFE
|CHASE_PROHIBIT_SYMLINKS
, /* ret_path= */ NULL
, &inode_fd
);
324 if (fstat(inode_fd
, &st
) < 0)
325 return negative_errno();
327 /* Paranoid safety check */
328 if (uid_is_system(st
.st_uid
) || gid_is_system(st
.st_gid
))
331 *ret_uid
= st
.st_uid
;
332 *ret_gid
= st
.st_gid
;
334 return TAKE_FD(inode_fd
);
337 static int bus_set_address_capsule(sd_bus
*bus
, const char *capsule
, const char *suffix
, int *ret_pin_fd
) {
338 _cleanup_close_
int inode_fd
= -EBADF
;
339 _cleanup_free_
char *pp
= NULL
;
349 /* Connects to a capsule's user bus. We need to do so under the capsule's UID/GID, otherwise
350 * the service manager might refuse our connection. Hence fake it. */
352 r
= capsule_name_is_valid(capsule
);
358 inode_fd
= pin_capsule_socket(capsule
, suffix
, &uid
, &gid
);
362 pp
= bus_address_escape(FORMAT_PROC_FD_PATH(inode_fd
));
366 if (asprintf(&bus
->address
, "unix:path=%s,uid=" UID_FMT
",gid=" GID_FMT
, pp
, uid
, gid
) < 0)
369 *ret_pin_fd
= TAKE_FD(inode_fd
); /* This fd must be kept pinned until the connection has been established */
373 int bus_set_address_capsule_bus(sd_bus
*bus
, const char *capsule
, int *ret_pin_fd
) {
374 return bus_set_address_capsule(bus
, capsule
, "bus", ret_pin_fd
);
377 int bus_connect_capsule_systemd(const char *capsule
, sd_bus
**ret
) {
378 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
379 _cleanup_close_
int inode_fd
= -EBADF
;
385 r
= sd_bus_new(&bus
);
389 r
= bus_set_address_capsule(bus
, capsule
, "systemd/private", &inode_fd
);
393 r
= sd_bus_start(bus
);
397 *ret
= TAKE_PTR(bus
);
401 int bus_connect_capsule_bus(const char *capsule
, sd_bus
**ret
) {
402 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
403 _cleanup_close_
int inode_fd
= -EBADF
;
409 r
= sd_bus_new(&bus
);
413 r
= bus_set_address_capsule_bus(bus
, capsule
, &inode_fd
);
417 r
= sd_bus_set_bus_client(bus
, true);
421 r
= sd_bus_start(bus
);
425 *ret
= TAKE_PTR(bus
);
429 int bus_connect_transport(
430 BusTransport transport
,
432 RuntimeScope runtime_scope
,
435 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
438 assert(transport
>= 0);
439 assert(transport
< _BUS_TRANSPORT_MAX
);
444 case BUS_TRANSPORT_LOCAL
:
445 assert_return(!host
, -EINVAL
);
447 switch (runtime_scope
) {
449 case RUNTIME_SCOPE_USER
:
450 r
= sd_bus_default_user(&bus
);
453 case RUNTIME_SCOPE_SYSTEM
:
454 if (sd_booted() <= 0)
455 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
456 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
457 "System has not been booted with systemd as init system (PID 1). Can't operate.");
459 r
= sd_bus_default_system(&bus
);
463 assert_not_reached();
467 case BUS_TRANSPORT_REMOTE
:
468 assert_return(runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
470 r
= sd_bus_open_system_remote(&bus
, host
);
473 case BUS_TRANSPORT_MACHINE
:
474 switch (runtime_scope
) {
476 case RUNTIME_SCOPE_USER
:
477 r
= sd_bus_open_user_machine(&bus
, host
);
480 case RUNTIME_SCOPE_SYSTEM
:
481 r
= sd_bus_open_system_machine(&bus
, host
);
485 assert_not_reached();
490 case BUS_TRANSPORT_CAPSULE
:
491 assert_return(runtime_scope
== RUNTIME_SCOPE_USER
, -EINVAL
);
493 r
= bus_connect_capsule_bus(host
, &bus
);
497 assert_not_reached();
502 r
= sd_bus_set_exit_on_disconnect(bus
, true);
506 *ret
= TAKE_PTR(bus
);
510 int bus_connect_transport_systemd(
511 BusTransport transport
,
513 RuntimeScope runtime_scope
,
518 assert(transport
>= 0);
519 assert(transport
< _BUS_TRANSPORT_MAX
);
524 case BUS_TRANSPORT_LOCAL
:
525 assert_return(!host
, -EINVAL
);
527 switch (runtime_scope
) {
529 case RUNTIME_SCOPE_USER
:
530 r
= bus_connect_user_systemd(ret
);
531 /* We used to always fall back to the user session bus if we couldn't connect to the
532 * private manager bus. To keep compat with existing code that was setting
533 * DBUS_SESSION_BUS_ADDRESS without setting XDG_RUNTIME_DIR, connect to the user
534 * session bus if DBUS_SESSION_BUS_ADDRESS is set and XDG_RUNTIME_DIR isn't. */
535 if (r
== -ENOMEDIUM
&& secure_getenv("DBUS_SESSION_BUS_ADDRESS")) {
536 log_debug_errno(r
, "$XDG_RUNTIME_DIR not set, unable to connect to private bus. Falling back to session bus.");
537 r
= sd_bus_default_user(ret
);
542 case RUNTIME_SCOPE_SYSTEM
:
543 if (sd_booted() <= 0)
544 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
545 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
546 "System has not been booted with systemd as init system (PID 1). Can't operate.");
548 /* If we are root then let's talk directly to the system instance, instead of
549 * going via the bus. */
551 return bus_connect_system_systemd(ret
);
553 return sd_bus_default_system(ret
);
556 assert_not_reached();
561 case BUS_TRANSPORT_REMOTE
:
562 assert_return(runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
563 return sd_bus_open_system_remote(ret
, host
);
565 case BUS_TRANSPORT_MACHINE
:
566 assert_return(runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
567 return sd_bus_open_system_machine(ret
, host
);
569 case BUS_TRANSPORT_CAPSULE
:
570 assert_return(runtime_scope
== RUNTIME_SCOPE_USER
, -EINVAL
);
571 return bus_connect_capsule_systemd(host
, ret
);
574 assert_not_reached();
579 * bus_path_encode_unique() - encode unique object path
580 * @b: bus connection or NULL
581 * @prefix: object path prefix
582 * @sender_id: unique-name of client, or NULL
583 * @external_id: external ID to be chosen by client, or NULL
584 * @ret_path: storage for encoded object path pointer
586 * Whenever we provide a bus API that allows clients to create and manage
587 * server-side objects, we need to provide a unique name for these objects. If
588 * we let the server choose the name, we suffer from a race condition: If a
589 * client creates an object asynchronously, it cannot destroy that object until
590 * it received the method reply. It cannot know the name of the new object,
591 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
593 * Therefore, many APIs allow the client to choose the unique name for newly
594 * created objects. There're two problems to solve, though:
595 * 1) Object names are usually defined via dbus object paths, which are
596 * usually globally namespaced. Therefore, multiple clients must be able
597 * to choose unique object names without interference.
598 * 2) If multiple libraries share the same bus connection, they must be
599 * able to choose unique object names without interference.
600 * The first problem is solved easily by prefixing a name with the
601 * unique-bus-name of a connection. The server side must enforce this and
602 * reject any other name. The second problem is solved by providing unique
603 * suffixes from within sd-bus.
605 * This helper allows clients to create unique object-paths. It uses the
606 * template '/prefix/sender_id/external_id' and returns the new path in
607 * @ret_path (must be freed by the caller).
608 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
609 * NULL, this function allocates a unique suffix via @b (by requesting a new
610 * cookie). If both @sender_id and @external_id are given, @b can be passed as
613 * Returns: 0 on success, negative error code on failure.
615 int bus_path_encode_unique(sd_bus
*b
, const char *prefix
, const char *sender_id
, const char *external_id
, char **ret_path
) {
616 _cleanup_free_
char *sender_label
= NULL
, *external_label
= NULL
;
617 char external_buf
[DECIMAL_STR_MAX(uint64_t)], *p
;
620 assert_return(b
|| (sender_id
&& external_id
), -EINVAL
);
621 assert_return(sd_bus_object_path_is_valid(prefix
), -EINVAL
);
622 assert_return(ret_path
, -EINVAL
);
625 r
= sd_bus_get_unique_name(b
, &sender_id
);
631 xsprintf(external_buf
, "%"PRIu64
, ++b
->cookie
);
632 external_id
= external_buf
;
635 sender_label
= bus_label_escape(sender_id
);
639 external_label
= bus_label_escape(external_id
);
643 p
= path_join(prefix
, sender_label
, external_label
);
652 * bus_path_decode_unique() - decode unique object path
653 * @path: object path to decode
654 * @prefix: object path prefix
655 * @ret_sender: output parameter for sender-id label
656 * @ret_external: output parameter for external-id label
658 * This does the reverse of bus_path_encode_unique() (see its description for
659 * details). Both trailing labels, sender-id and external-id, are unescaped and
660 * returned in the given output parameters (the caller must free them).
662 * Note that this function returns 0 if the path does not match the template
663 * (see bus_path_encode_unique()), 1 if it matched.
665 * Returns: Negative error code on failure, 0 if the given object path does not
666 * match the template (return parameters are set to NULL), 1 if it was
667 * parsed successfully (return parameters contain allocated labels).
669 int bus_path_decode_unique(const char *path
, const char *prefix
, char **ret_sender
, char **ret_external
) {
671 char *sender
, *external
;
673 assert(sd_bus_object_path_is_valid(path
));
674 assert(sd_bus_object_path_is_valid(prefix
));
676 assert(ret_external
);
678 p
= object_path_startswith(path
, prefix
);
681 *ret_external
= NULL
;
688 *ret_external
= NULL
;
692 sender
= bus_label_unescape_n(p
, q
- p
);
693 external
= bus_label_unescape(q
+ 1);
694 if (!sender
|| !external
) {
700 *ret_sender
= sender
;
701 *ret_external
= external
;
705 int bus_track_add_name_many(sd_bus_track
*t
, char * const *l
) {
710 /* Continues adding after failure, and returns the first failure. */
713 RET_GATHER(r
, sd_bus_track_add_name(t
, *i
));
717 int bus_track_to_strv(sd_bus_track
*t
, char ***ret
) {
718 _cleanup_strv_free_
char **subscribed
= NULL
;
723 for (const char *n
= sd_bus_track_first(t
); n
; n
= sd_bus_track_next(t
)) {
724 int c
= sd_bus_track_count_name(t
, n
);
727 for (int j
= 0; j
< c
; j
++) {
728 r
= strv_extend(&subscribed
, n
);
734 *ret
= TAKE_PTR(subscribed
);
738 int bus_open_system_watch_bind_with_description(sd_bus
**ret
, const char *description
) {
739 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
745 /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal
748 r
= sd_bus_new(&bus
);
753 r
= sd_bus_set_description(bus
, description
);
758 e
= secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
760 e
= DEFAULT_SYSTEM_BUS_ADDRESS
;
762 r
= sd_bus_set_address(bus
, e
);
766 r
= sd_bus_set_bus_client(bus
, true);
770 r
= sd_bus_negotiate_creds(bus
, true, SD_BUS_CREDS_UID
|SD_BUS_CREDS_EUID
|SD_BUS_CREDS_EFFECTIVE_CAPS
);
774 r
= sd_bus_set_watch_bind(bus
, true);
778 r
= sd_bus_set_connected_signal(bus
, true);
782 r
= sd_bus_start(bus
);
786 *ret
= TAKE_PTR(bus
);
791 int bus_reply_pair_array(sd_bus_message
*m
, char * const *l
) {
792 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
797 /* Reply to the specified message with a message containing a dictionary put together from the
800 r
= sd_bus_message_new_method_return(m
, &reply
);
804 r
= sd_bus_message_open_container(reply
, 'a', "{ss}");
808 STRV_FOREACH_PAIR(k
, v
, l
) {
809 r
= sd_bus_message_append(reply
, "{ss}", *k
, *v
);
814 r
= sd_bus_message_close_container(reply
);
818 return sd_bus_message_send(reply
);
821 static int method_dump_memory_state_by_fd(sd_bus_message
*message
, void *userdata
, sd_bus_error
*reterr_error
) {
822 _cleanup_(memstream_done
) MemStream m
= {};
823 _cleanup_free_
char *dump
= NULL
;
824 _cleanup_close_
int fd
= -EBADF
;
831 f
= memstream_init(&m
);
835 r
= RET_NERRNO(malloc_info(/* options= */ 0, f
));
839 r
= memstream_finalize(&m
, &dump
, &dump_size
);
843 fd
= memfd_new_and_seal("malloc-info", dump
, dump_size
);
847 r
= sd_bus_reply_method_return(message
, "h", fd
);
851 return 1; /* Stop further processing */
854 /* The default install callback will fail and disconnect the bus if it cannot register the match, but this
855 * is only a debug method, we definitely don't want to fail in case there's some permission issue. */
856 static int dummy_install_callback(sd_bus_message
*message
, void *userdata
, sd_bus_error
*reterr_error
) {
860 int bus_register_malloc_status(sd_bus
*bus
, const char *destination
) {
865 assert(!isempty(destination
));
867 match
= strjoina("type='method_call',"
868 "interface='org.freedesktop.MemoryAllocation1',"
869 "path='/org/freedesktop/MemoryAllocation1',"
870 "destination='", destination
, "',",
871 "member='GetMallocInfo'");
873 r
= sd_bus_add_match_async(bus
, NULL
, match
, method_dump_memory_state_by_fd
, dummy_install_callback
, NULL
);
875 return log_debug_errno(r
, "Failed to subscribe to GetMallocInfo() calls on MemoryAllocation1 interface: %m");
880 int bus_creds_get_pidref(
891 r
= sd_bus_creds_get_pid(c
, &pid
);
895 r
= sd_bus_creds_get_pidfd_dup(c
, &pidfd
);
896 if (r
< 0 && r
!= -ENODATA
)
907 int bus_query_sender_pidref(
911 _cleanup_(sd_bus_creds_unrefp
) sd_bus_creds
*creds
= NULL
;
917 r
= sd_bus_query_sender_creds(m
, SD_BUS_CREDS_PID
|SD_BUS_CREDS_PIDFD
, &creds
);
921 return bus_creds_get_pidref(creds
, ret
);
924 int bus_get_instance_id(sd_bus
*bus
, sd_id128_t
*ret
) {
925 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
931 r
= sd_bus_call_method(bus
,
932 "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetId",
933 /* reterr_error = */ NULL
, &reply
, NULL
);
939 r
= sd_bus_message_read_basic(reply
, 's', &id
);
943 return sd_id128_from_string(id
, ret
);
946 static const char* const bus_transport_table
[] = {
947 [BUS_TRANSPORT_LOCAL
] = "local",
948 [BUS_TRANSPORT_REMOTE
] = "remote",
949 [BUS_TRANSPORT_MACHINE
] = "machine",
950 [BUS_TRANSPORT_CAPSULE
] = "capsule",
953 DEFINE_STRING_TABLE_LOOKUP_TO_STRING(bus_transport
, BusTransport
);