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 "daemon-util.h"
22 #include "data-fd-util.h"
24 #include "memstream-util.h"
25 #include "path-util.h"
26 #include "socket-util.h"
27 #include "stdio-util.h"
29 static int name_owner_change_callback(sd_bus_message
*m
, void *userdata
, sd_bus_error
*ret_error
) {
30 sd_event
*e
= ASSERT_PTR(userdata
);
34 sd_bus_close(sd_bus_message_get_bus(m
));
40 int bus_log_address_error(int r
, BusTransport transport
) {
41 bool hint
= transport
== BUS_TRANSPORT_LOCAL
&& r
== -ENOMEDIUM
;
43 return log_error_errno(r
,
44 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)" :
45 "Failed to set bus address: %m");
48 int bus_log_connect_error(int r
, BusTransport transport
) {
49 bool hint_vars
= transport
== BUS_TRANSPORT_LOCAL
&& r
== -ENOMEDIUM
,
50 hint_addr
= transport
== BUS_TRANSPORT_LOCAL
&& ERRNO_IS_PRIVILEGE(r
);
52 return log_error_errno(r
,
53 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)" :
54 r
== hint_addr
? "Failed to connect to bus: Operation not permitted (consider using --machine=<user>@.host --user to connect to bus of other user)" :
55 "Failed to connect to bus: %m");
58 int bus_async_unregister_and_exit(sd_event
*e
, sd_bus
*bus
, const char *name
) {
67 /* We unregister the name here and then wait for the
68 * NameOwnerChanged signal for this event to arrive before we
69 * quit. We do this in order to make sure that any queued
70 * requests are still processed before we really exit. */
72 r
= sd_bus_get_unique_name(bus
, &unique
);
77 "sender='org.freedesktop.DBus',"
79 "interface='org.freedesktop.DBus',"
80 "member='NameOwnerChanged',"
81 "path='/org/freedesktop/DBus',"
83 "arg1='", unique
, "',",
86 r
= sd_bus_add_match_async(bus
, NULL
, match
, name_owner_change_callback
, NULL
, e
);
90 r
= sd_bus_release_name_async(bus
, NULL
, name
, NULL
, NULL
);
97 int bus_event_loop_with_idle(
102 check_idle_t check_idle
,
105 bool exiting
= false;
115 r
= sd_event_get_state(e
);
118 if (r
== SD_EVENT_FINISHED
)
122 idle
= check_idle(userdata
);
126 r
= sd_event_run(e
, exiting
|| !idle
? UINT64_MAX
: timeout
);
130 if (r
== 0 && !exiting
&& idle
) {
131 /* Inform the service manager that we are going down, so that it will queue all
132 * further start requests, instead of assuming we are still running. */
133 (void) sd_notify(false, NOTIFY_STOPPING
);
135 r
= bus_async_unregister_and_exit(e
, bus
, name
);
143 r
= sd_event_get_exit_code(e
, &code
);
150 int bus_name_has_owner(sd_bus
*c
, const char *name
, sd_bus_error
*error
) {
151 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*rep
= NULL
;
152 int r
, has_owner
= 0;
157 r
= sd_bus_call_method(c
,
158 "org.freedesktop.DBus",
159 "/org/freedesktop/dbus",
160 "org.freedesktop.DBus",
169 r
= sd_bus_message_read_basic(rep
, 'b', &has_owner
);
171 return sd_bus_error_set_errno(error
, r
);
176 bool bus_error_is_unknown_service(const sd_bus_error
*error
) {
177 return sd_bus_error_has_names(error
,
178 SD_BUS_ERROR_SERVICE_UNKNOWN
,
179 SD_BUS_ERROR_NAME_HAS_NO_OWNER
,
180 BUS_ERROR_NO_SUCH_UNIT
);
183 int bus_check_peercred(sd_bus
*c
) {
189 fd
= sd_bus_get_fd(c
);
193 r
= getpeercred(fd
, &ucred
);
197 if (ucred
.uid
!= 0 && ucred
.uid
!= geteuid())
203 int bus_connect_system_systemd(sd_bus
**ret_bus
) {
204 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
210 return sd_bus_default_system(ret_bus
);
212 /* If we are root then let's talk directly to the system
213 * instance, instead of going via the bus */
215 r
= sd_bus_new(&bus
);
219 r
= sd_bus_set_address(bus
, "unix:path=/run/systemd/private");
223 r
= sd_bus_start(bus
);
225 return sd_bus_default_system(ret_bus
);
227 r
= bus_check_peercred(bus
);
231 *ret_bus
= TAKE_PTR(bus
);
235 int bus_connect_user_systemd(sd_bus
**ret_bus
) {
236 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
237 _cleanup_free_
char *ee
= NULL
;
243 e
= secure_getenv("XDG_RUNTIME_DIR");
245 return sd_bus_default_user(ret_bus
);
247 ee
= bus_address_escape(e
);
251 r
= sd_bus_new(&bus
);
255 bus
->address
= strjoin("unix:path=", ee
, "/systemd/private");
259 r
= sd_bus_start(bus
);
261 return sd_bus_default_user(ret_bus
);
263 r
= bus_check_peercred(bus
);
267 *ret_bus
= TAKE_PTR(bus
);
271 int bus_connect_transport(
272 BusTransport transport
,
274 RuntimeScope runtime_scope
,
277 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
280 assert(transport
>= 0);
281 assert(transport
< _BUS_TRANSPORT_MAX
);
284 assert_return((transport
== BUS_TRANSPORT_LOCAL
) == !host
, -EINVAL
);
285 assert_return(transport
!= BUS_TRANSPORT_REMOTE
|| runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
289 case BUS_TRANSPORT_LOCAL
:
291 switch (runtime_scope
) {
293 case RUNTIME_SCOPE_USER
:
294 r
= sd_bus_default_user(&bus
);
297 case RUNTIME_SCOPE_SYSTEM
:
298 if (sd_booted() <= 0)
299 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
300 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
301 "System has not been booted with systemd as init system (PID 1). Can't operate.");
302 r
= sd_bus_default_system(&bus
);
306 assert_not_reached();
310 case BUS_TRANSPORT_REMOTE
:
311 r
= sd_bus_open_system_remote(&bus
, host
);
314 case BUS_TRANSPORT_MACHINE
:
316 switch (runtime_scope
) {
318 case RUNTIME_SCOPE_USER
:
319 r
= sd_bus_open_user_machine(&bus
, host
);
322 case RUNTIME_SCOPE_SYSTEM
:
323 r
= sd_bus_open_system_machine(&bus
, host
);
327 assert_not_reached();
333 assert_not_reached();
338 r
= sd_bus_set_exit_on_disconnect(bus
, true);
342 *ret
= TAKE_PTR(bus
);
346 int bus_connect_transport_systemd(BusTransport transport
, const char *host
, RuntimeScope runtime_scope
, sd_bus
**bus
) {
347 assert(transport
>= 0);
348 assert(transport
< _BUS_TRANSPORT_MAX
);
351 assert_return((transport
== BUS_TRANSPORT_LOCAL
) == !host
, -EINVAL
);
352 assert_return(transport
== BUS_TRANSPORT_LOCAL
|| runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
356 case BUS_TRANSPORT_LOCAL
:
357 switch (runtime_scope
) {
359 case RUNTIME_SCOPE_USER
:
360 return bus_connect_user_systemd(bus
);
362 case RUNTIME_SCOPE_SYSTEM
:
363 if (sd_booted() <= 0)
364 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
365 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
366 "System has not been booted with systemd as init system (PID 1). Can't operate.");
367 return bus_connect_system_systemd(bus
);
370 assert_not_reached();
375 case BUS_TRANSPORT_REMOTE
:
376 return sd_bus_open_system_remote(bus
, host
);
378 case BUS_TRANSPORT_MACHINE
:
379 return sd_bus_open_system_machine(bus
, host
);
382 assert_not_reached();
387 * bus_path_encode_unique() - encode unique object path
388 * @b: bus connection or NULL
389 * @prefix: object path prefix
390 * @sender_id: unique-name of client, or NULL
391 * @external_id: external ID to be chosen by client, or NULL
392 * @ret_path: storage for encoded object path pointer
394 * Whenever we provide a bus API that allows clients to create and manage
395 * server-side objects, we need to provide a unique name for these objects. If
396 * we let the server choose the name, we suffer from a race condition: If a
397 * client creates an object asynchronously, it cannot destroy that object until
398 * it received the method reply. It cannot know the name of the new object,
399 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
401 * Therefore, many APIs allow the client to choose the unique name for newly
402 * created objects. There're two problems to solve, though:
403 * 1) Object names are usually defined via dbus object paths, which are
404 * usually globally namespaced. Therefore, multiple clients must be able
405 * to choose unique object names without interference.
406 * 2) If multiple libraries share the same bus connection, they must be
407 * able to choose unique object names without interference.
408 * The first problem is solved easily by prefixing a name with the
409 * unique-bus-name of a connection. The server side must enforce this and
410 * reject any other name. The second problem is solved by providing unique
411 * suffixes from within sd-bus.
413 * This helper allows clients to create unique object-paths. It uses the
414 * template '/prefix/sender_id/external_id' and returns the new path in
415 * @ret_path (must be freed by the caller).
416 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
417 * NULL, this function allocates a unique suffix via @b (by requesting a new
418 * cookie). If both @sender_id and @external_id are given, @b can be passed as
421 * Returns: 0 on success, negative error code on failure.
423 int bus_path_encode_unique(sd_bus
*b
, const char *prefix
, const char *sender_id
, const char *external_id
, char **ret_path
) {
424 _cleanup_free_
char *sender_label
= NULL
, *external_label
= NULL
;
425 char external_buf
[DECIMAL_STR_MAX(uint64_t)], *p
;
428 assert_return(b
|| (sender_id
&& external_id
), -EINVAL
);
429 assert_return(sd_bus_object_path_is_valid(prefix
), -EINVAL
);
430 assert_return(ret_path
, -EINVAL
);
433 r
= sd_bus_get_unique_name(b
, &sender_id
);
439 xsprintf(external_buf
, "%"PRIu64
, ++b
->cookie
);
440 external_id
= external_buf
;
443 sender_label
= bus_label_escape(sender_id
);
447 external_label
= bus_label_escape(external_id
);
451 p
= path_join(prefix
, sender_label
, external_label
);
460 * bus_path_decode_unique() - decode unique object path
461 * @path: object path to decode
462 * @prefix: object path prefix
463 * @ret_sender: output parameter for sender-id label
464 * @ret_external: output parameter for external-id label
466 * This does the reverse of bus_path_encode_unique() (see its description for
467 * details). Both trailing labels, sender-id and external-id, are unescaped and
468 * returned in the given output parameters (the caller must free them).
470 * Note that this function returns 0 if the path does not match the template
471 * (see bus_path_encode_unique()), 1 if it matched.
473 * Returns: Negative error code on failure, 0 if the given object path does not
474 * match the template (return parameters are set to NULL), 1 if it was
475 * parsed successfully (return parameters contain allocated labels).
477 int bus_path_decode_unique(const char *path
, const char *prefix
, char **ret_sender
, char **ret_external
) {
479 char *sender
, *external
;
481 assert(sd_bus_object_path_is_valid(path
));
482 assert(sd_bus_object_path_is_valid(prefix
));
484 assert(ret_external
);
486 p
= object_path_startswith(path
, prefix
);
489 *ret_external
= NULL
;
496 *ret_external
= NULL
;
500 sender
= bus_label_unescape_n(p
, q
- p
);
501 external
= bus_label_unescape(q
+ 1);
502 if (!sender
|| !external
) {
508 *ret_sender
= sender
;
509 *ret_external
= external
;
513 int bus_track_add_name_many(sd_bus_track
*t
, char **l
) {
518 /* Continues adding after failure, and returns the first failure. */
521 RET_GATHER(r
, sd_bus_track_add_name(t
, *i
));
525 int bus_open_system_watch_bind_with_description(sd_bus
**ret
, const char *description
) {
526 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
532 /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal
535 r
= sd_bus_new(&bus
);
540 r
= sd_bus_set_description(bus
, description
);
545 e
= secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
547 e
= DEFAULT_SYSTEM_BUS_ADDRESS
;
549 r
= sd_bus_set_address(bus
, e
);
553 r
= sd_bus_set_bus_client(bus
, true);
557 r
= sd_bus_negotiate_creds(bus
, true, SD_BUS_CREDS_UID
|SD_BUS_CREDS_EUID
|SD_BUS_CREDS_EFFECTIVE_CAPS
);
561 r
= sd_bus_set_watch_bind(bus
, true);
565 r
= sd_bus_set_connected_signal(bus
, true);
569 r
= sd_bus_start(bus
);
573 *ret
= TAKE_PTR(bus
);
578 int bus_reply_pair_array(sd_bus_message
*m
, char **l
) {
579 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
584 /* Reply to the specified message with a message containing a dictionary put together from the
587 r
= sd_bus_message_new_method_return(m
, &reply
);
591 r
= sd_bus_message_open_container(reply
, 'a', "{ss}");
595 STRV_FOREACH_PAIR(k
, v
, l
) {
596 r
= sd_bus_message_append(reply
, "{ss}", *k
, *v
);
601 r
= sd_bus_message_close_container(reply
);
605 return sd_bus_send(NULL
, reply
, NULL
);
608 static int method_dump_memory_state_by_fd(sd_bus_message
*message
, void *userdata
, sd_bus_error
*ret_error
) {
609 _cleanup_(memstream_done
) MemStream m
= {};
610 _cleanup_free_
char *dump
= NULL
;
611 _cleanup_close_
int fd
= -EBADF
;
618 f
= memstream_init(&m
);
622 r
= RET_NERRNO(malloc_info(/* options= */ 0, f
));
626 r
= memstream_finalize(&m
, &dump
, &dump_size
);
630 fd
= acquire_data_fd(dump
, dump_size
, 0);
634 r
= sd_bus_reply_method_return(message
, "h", fd
);
638 return 1; /* Stop further processing */
641 /* The default install callback will fail and disconnect the bus if it cannot register the match, but this
642 * is only a debug method, we definitely don't want to fail in case there's some permission issue. */
643 static int dummy_install_callback(sd_bus_message
*message
, void *userdata
, sd_bus_error
*ret_error
) {
647 int bus_register_malloc_status(sd_bus
*bus
, const char *destination
) {
652 assert(!isempty(destination
));
654 match
= strjoina("type='method_call',"
655 "interface='org.freedesktop.MemoryAllocation1',"
656 "path='/org/freedesktop/MemoryAllocation1',"
657 "destination='", destination
, "',",
658 "member='GetMallocInfo'");
660 r
= sd_bus_add_match_async(bus
, NULL
, match
, method_dump_memory_state_by_fd
, dummy_install_callback
, NULL
);
662 return log_debug_errno(r
, "Failed to subscribe to GetMallocInfo() calls on MemoryAllocation1 interface: %m");
667 static void bus_message_unref_wrapper(void *m
) {
668 sd_bus_message_unref(m
);
671 const struct hash_ops bus_message_hash_ops
= {
672 .hash
= trivial_hash_func
,
673 .compare
= trivial_compare_func
,
674 .free_value
= bus_message_unref_wrapper
,
677 int bus_message_append_string_set(sd_bus_message
*m
, Set
*set
) {
683 r
= sd_bus_message_open_container(m
, 'a', "s");
687 SET_FOREACH(s
, set
) {
688 r
= sd_bus_message_append(m
, "s", s
);
693 return sd_bus_message_close_container(m
);
696 int bus_property_get_string_set(
699 const char *interface
,
700 const char *property
,
701 sd_bus_message
*reply
,
703 sd_bus_error
*error
) {
705 Set
**s
= ASSERT_PTR(userdata
);
711 return bus_message_append_string_set(reply
, *s
);
714 int bus_creds_get_pidref(
725 r
= sd_bus_creds_get_pid(c
, &pid
);
729 r
= sd_bus_creds_get_pidfd_dup(c
, &pidfd
);
730 if (r
< 0 && r
!= -ENODATA
)
741 int bus_query_sender_pidref(
745 _cleanup_(sd_bus_creds_unrefp
) sd_bus_creds
*creds
= NULL
;
751 r
= sd_bus_query_sender_creds(m
, SD_BUS_CREDS_PID
|SD_BUS_CREDS_PIDFD
, &creds
);
755 return bus_creds_get_pidref(creds
, ret
);