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
;
286 p
= path_join("/run/capsules", capsule
, suffix
);
290 /* We enter territory owned by the user, hence let's be paranoid about symlinks and ownership */
291 r
= chase(p
, /* root= */ NULL
, CHASE_SAFE
|CHASE_PROHIBIT_SYMLINKS
, /* ret_path= */ NULL
, &inode_fd
);
295 if (fstat(inode_fd
, &st
) < 0)
296 return negative_errno();
298 /* Paranoid safety check */
299 if (uid_is_system(st
.st_uid
) || gid_is_system(st
.st_gid
))
302 *ret_uid
= st
.st_uid
;
303 *ret_gid
= st
.st_gid
;
305 return TAKE_FD(inode_fd
);
308 static int bus_set_address_capsule(sd_bus
*bus
, const char *capsule
, const char *suffix
, int *ret_pin_fd
) {
309 _cleanup_close_
int inode_fd
= -EBADF
;
310 _cleanup_free_
char *pp
= NULL
;
320 /* Connects to a capsule's user bus. We need to do so under the capsule's UID/GID, otherwise
321 * the service manager might refuse our connection. Hence fake it. */
323 r
= capsule_name_is_valid(capsule
);
329 inode_fd
= pin_capsule_socket(capsule
, suffix
, &uid
, &gid
);
333 pp
= bus_address_escape(FORMAT_PROC_FD_PATH(inode_fd
));
337 if (asprintf(&bus
->address
, "unix:path=%s,uid=" UID_FMT
",gid=" GID_FMT
, pp
, uid
, gid
) < 0)
340 *ret_pin_fd
= TAKE_FD(inode_fd
); /* This fd must be kept pinned until the connection has been established */
344 int bus_set_address_capsule_bus(sd_bus
*bus
, const char *capsule
, int *ret_pin_fd
) {
345 return bus_set_address_capsule(bus
, capsule
, "bus", ret_pin_fd
);
348 int bus_connect_capsule_systemd(const char *capsule
, sd_bus
**ret_bus
) {
349 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
350 _cleanup_close_
int inode_fd
= -EBADF
;
356 r
= sd_bus_new(&bus
);
360 r
= bus_set_address_capsule(bus
, capsule
, "systemd/private", &inode_fd
);
364 r
= sd_bus_start(bus
);
368 *ret_bus
= TAKE_PTR(bus
);
372 int bus_connect_capsule_bus(const char *capsule
, sd_bus
**ret_bus
) {
373 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
374 _cleanup_close_
int inode_fd
= -EBADF
;
380 r
= sd_bus_new(&bus
);
384 r
= bus_set_address_capsule_bus(bus
, capsule
, &inode_fd
);
388 r
= sd_bus_set_bus_client(bus
, true);
392 r
= sd_bus_start(bus
);
396 *ret_bus
= TAKE_PTR(bus
);
400 int bus_connect_transport(
401 BusTransport transport
,
403 RuntimeScope runtime_scope
,
406 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
409 assert(transport
>= 0);
410 assert(transport
< _BUS_TRANSPORT_MAX
);
415 case BUS_TRANSPORT_LOCAL
:
416 assert_return(!host
, -EINVAL
);
418 switch (runtime_scope
) {
420 case RUNTIME_SCOPE_USER
:
421 r
= sd_bus_default_user(&bus
);
424 case RUNTIME_SCOPE_SYSTEM
:
425 if (sd_booted() <= 0)
426 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
427 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
428 "System has not been booted with systemd as init system (PID 1). Can't operate.");
429 r
= sd_bus_default_system(&bus
);
433 assert_not_reached();
437 case BUS_TRANSPORT_REMOTE
:
438 assert_return(runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
440 r
= sd_bus_open_system_remote(&bus
, host
);
443 case BUS_TRANSPORT_MACHINE
:
444 switch (runtime_scope
) {
446 case RUNTIME_SCOPE_USER
:
447 r
= sd_bus_open_user_machine(&bus
, host
);
450 case RUNTIME_SCOPE_SYSTEM
:
451 r
= sd_bus_open_system_machine(&bus
, host
);
455 assert_not_reached();
460 case BUS_TRANSPORT_CAPSULE
:
461 assert_return(runtime_scope
== RUNTIME_SCOPE_USER
, -EINVAL
);
463 r
= bus_connect_capsule_bus(host
, &bus
);
467 assert_not_reached();
472 r
= sd_bus_set_exit_on_disconnect(bus
, true);
476 *ret
= TAKE_PTR(bus
);
480 int bus_connect_transport_systemd(
481 BusTransport transport
,
483 RuntimeScope runtime_scope
,
486 assert(transport
>= 0);
487 assert(transport
< _BUS_TRANSPORT_MAX
);
492 case BUS_TRANSPORT_LOCAL
:
493 assert_return(!host
, -EINVAL
);
495 switch (runtime_scope
) {
497 case RUNTIME_SCOPE_USER
:
498 return bus_connect_user_systemd(ret_bus
);
500 case RUNTIME_SCOPE_SYSTEM
:
501 if (sd_booted() <= 0)
502 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
503 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
504 "System has not been booted with systemd as init system (PID 1). Can't operate.");
505 return bus_connect_system_systemd(ret_bus
);
508 assert_not_reached();
513 case BUS_TRANSPORT_REMOTE
:
514 assert_return(runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
515 return sd_bus_open_system_remote(ret_bus
, host
);
517 case BUS_TRANSPORT_MACHINE
:
518 assert_return(runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
519 return sd_bus_open_system_machine(ret_bus
, host
);
521 case BUS_TRANSPORT_CAPSULE
:
522 assert_return(runtime_scope
== RUNTIME_SCOPE_USER
, -EINVAL
);
523 return bus_connect_capsule_systemd(host
, ret_bus
);
526 assert_not_reached();
531 * bus_path_encode_unique() - encode unique object path
532 * @b: bus connection or NULL
533 * @prefix: object path prefix
534 * @sender_id: unique-name of client, or NULL
535 * @external_id: external ID to be chosen by client, or NULL
536 * @ret_path: storage for encoded object path pointer
538 * Whenever we provide a bus API that allows clients to create and manage
539 * server-side objects, we need to provide a unique name for these objects. If
540 * we let the server choose the name, we suffer from a race condition: If a
541 * client creates an object asynchronously, it cannot destroy that object until
542 * it received the method reply. It cannot know the name of the new object,
543 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
545 * Therefore, many APIs allow the client to choose the unique name for newly
546 * created objects. There're two problems to solve, though:
547 * 1) Object names are usually defined via dbus object paths, which are
548 * usually globally namespaced. Therefore, multiple clients must be able
549 * to choose unique object names without interference.
550 * 2) If multiple libraries share the same bus connection, they must be
551 * able to choose unique object names without interference.
552 * The first problem is solved easily by prefixing a name with the
553 * unique-bus-name of a connection. The server side must enforce this and
554 * reject any other name. The second problem is solved by providing unique
555 * suffixes from within sd-bus.
557 * This helper allows clients to create unique object-paths. It uses the
558 * template '/prefix/sender_id/external_id' and returns the new path in
559 * @ret_path (must be freed by the caller).
560 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
561 * NULL, this function allocates a unique suffix via @b (by requesting a new
562 * cookie). If both @sender_id and @external_id are given, @b can be passed as
565 * Returns: 0 on success, negative error code on failure.
567 int bus_path_encode_unique(sd_bus
*b
, const char *prefix
, const char *sender_id
, const char *external_id
, char **ret_path
) {
568 _cleanup_free_
char *sender_label
= NULL
, *external_label
= NULL
;
569 char external_buf
[DECIMAL_STR_MAX(uint64_t)], *p
;
572 assert_return(b
|| (sender_id
&& external_id
), -EINVAL
);
573 assert_return(sd_bus_object_path_is_valid(prefix
), -EINVAL
);
574 assert_return(ret_path
, -EINVAL
);
577 r
= sd_bus_get_unique_name(b
, &sender_id
);
583 xsprintf(external_buf
, "%"PRIu64
, ++b
->cookie
);
584 external_id
= external_buf
;
587 sender_label
= bus_label_escape(sender_id
);
591 external_label
= bus_label_escape(external_id
);
595 p
= path_join(prefix
, sender_label
, external_label
);
604 * bus_path_decode_unique() - decode unique object path
605 * @path: object path to decode
606 * @prefix: object path prefix
607 * @ret_sender: output parameter for sender-id label
608 * @ret_external: output parameter for external-id label
610 * This does the reverse of bus_path_encode_unique() (see its description for
611 * details). Both trailing labels, sender-id and external-id, are unescaped and
612 * returned in the given output parameters (the caller must free them).
614 * Note that this function returns 0 if the path does not match the template
615 * (see bus_path_encode_unique()), 1 if it matched.
617 * Returns: Negative error code on failure, 0 if the given object path does not
618 * match the template (return parameters are set to NULL), 1 if it was
619 * parsed successfully (return parameters contain allocated labels).
621 int bus_path_decode_unique(const char *path
, const char *prefix
, char **ret_sender
, char **ret_external
) {
623 char *sender
, *external
;
625 assert(sd_bus_object_path_is_valid(path
));
626 assert(sd_bus_object_path_is_valid(prefix
));
628 assert(ret_external
);
630 p
= object_path_startswith(path
, prefix
);
633 *ret_external
= NULL
;
640 *ret_external
= NULL
;
644 sender
= bus_label_unescape_n(p
, q
- p
);
645 external
= bus_label_unescape(q
+ 1);
646 if (!sender
|| !external
) {
652 *ret_sender
= sender
;
653 *ret_external
= external
;
657 int bus_track_add_name_many(sd_bus_track
*t
, char **l
) {
662 /* Continues adding after failure, and returns the first failure. */
665 RET_GATHER(r
, sd_bus_track_add_name(t
, *i
));
669 int bus_open_system_watch_bind_with_description(sd_bus
**ret
, const char *description
) {
670 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
676 /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal
679 r
= sd_bus_new(&bus
);
684 r
= sd_bus_set_description(bus
, description
);
689 e
= secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
691 e
= DEFAULT_SYSTEM_BUS_ADDRESS
;
693 r
= sd_bus_set_address(bus
, e
);
697 r
= sd_bus_set_bus_client(bus
, true);
701 r
= sd_bus_negotiate_creds(bus
, true, SD_BUS_CREDS_UID
|SD_BUS_CREDS_EUID
|SD_BUS_CREDS_EFFECTIVE_CAPS
);
705 r
= sd_bus_set_watch_bind(bus
, true);
709 r
= sd_bus_set_connected_signal(bus
, true);
713 r
= sd_bus_start(bus
);
717 *ret
= TAKE_PTR(bus
);
722 int bus_reply_pair_array(sd_bus_message
*m
, char **l
) {
723 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
728 /* Reply to the specified message with a message containing a dictionary put together from the
731 r
= sd_bus_message_new_method_return(m
, &reply
);
735 r
= sd_bus_message_open_container(reply
, 'a', "{ss}");
739 STRV_FOREACH_PAIR(k
, v
, l
) {
740 r
= sd_bus_message_append(reply
, "{ss}", *k
, *v
);
745 r
= sd_bus_message_close_container(reply
);
749 return sd_bus_send(NULL
, reply
, NULL
);
752 static int method_dump_memory_state_by_fd(sd_bus_message
*message
, void *userdata
, sd_bus_error
*ret_error
) {
753 _cleanup_(memstream_done
) MemStream m
= {};
754 _cleanup_free_
char *dump
= NULL
;
755 _cleanup_close_
int fd
= -EBADF
;
762 f
= memstream_init(&m
);
766 r
= RET_NERRNO(malloc_info(/* options= */ 0, f
));
770 r
= memstream_finalize(&m
, &dump
, &dump_size
);
774 fd
= acquire_data_fd_full(dump
, dump_size
, /* flags = */ 0);
778 r
= sd_bus_reply_method_return(message
, "h", fd
);
782 return 1; /* Stop further processing */
785 /* The default install callback will fail and disconnect the bus if it cannot register the match, but this
786 * is only a debug method, we definitely don't want to fail in case there's some permission issue. */
787 static int dummy_install_callback(sd_bus_message
*message
, void *userdata
, sd_bus_error
*ret_error
) {
791 int bus_register_malloc_status(sd_bus
*bus
, const char *destination
) {
796 assert(!isempty(destination
));
798 match
= strjoina("type='method_call',"
799 "interface='org.freedesktop.MemoryAllocation1',"
800 "path='/org/freedesktop/MemoryAllocation1',"
801 "destination='", destination
, "',",
802 "member='GetMallocInfo'");
804 r
= sd_bus_add_match_async(bus
, NULL
, match
, method_dump_memory_state_by_fd
, dummy_install_callback
, NULL
);
806 return log_debug_errno(r
, "Failed to subscribe to GetMallocInfo() calls on MemoryAllocation1 interface: %m");
811 static void bus_message_unref_wrapper(void *m
) {
812 sd_bus_message_unref(m
);
815 const struct hash_ops bus_message_hash_ops
= {
816 .hash
= trivial_hash_func
,
817 .compare
= trivial_compare_func
,
818 .free_value
= bus_message_unref_wrapper
,
821 int bus_message_append_string_set(sd_bus_message
*m
, Set
*set
) {
827 r
= sd_bus_message_open_container(m
, 'a', "s");
831 SET_FOREACH(s
, set
) {
832 r
= sd_bus_message_append(m
, "s", s
);
837 return sd_bus_message_close_container(m
);
840 int bus_property_get_string_set(
843 const char *interface
,
844 const char *property
,
845 sd_bus_message
*reply
,
847 sd_bus_error
*error
) {
849 Set
**s
= ASSERT_PTR(userdata
);
855 return bus_message_append_string_set(reply
, *s
);
858 int bus_creds_get_pidref(
869 r
= sd_bus_creds_get_pid(c
, &pid
);
873 r
= sd_bus_creds_get_pidfd_dup(c
, &pidfd
);
874 if (r
< 0 && r
!= -ENODATA
)
885 int bus_query_sender_pidref(
889 _cleanup_(sd_bus_creds_unrefp
) sd_bus_creds
*creds
= NULL
;
895 r
= sd_bus_query_sender_creds(m
, SD_BUS_CREDS_PID
|SD_BUS_CREDS_PIDFD
, &creds
);
899 return bus_creds_get_pidref(creds
, ret
);
902 int bus_message_read_id128(sd_bus_message
*m
, sd_id128_t
*ret
) {
909 r
= sd_bus_message_read_array(m
, 'y', &a
, &sz
);
916 *ret
= SD_ID128_NULL
;
919 case sizeof(sd_id128_t
):
922 return !memeqzero(a
, sz
); /* This intends to sd_id128_is_null(), but ret may be NULL, so
923 * let'suse memeqzero() here. */