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 "data-fd-util.h"
23 #include "memstream-util.h"
24 #include "path-util.h"
25 #include "socket-util.h"
26 #include "stdio-util.h"
28 static int name_owner_change_callback(sd_bus_message
*m
, void *userdata
, sd_bus_error
*ret_error
) {
29 sd_event
*e
= ASSERT_PTR(userdata
);
33 sd_bus_close(sd_bus_message_get_bus(m
));
39 int bus_log_address_error(int r
, BusTransport transport
) {
40 bool hint
= transport
== BUS_TRANSPORT_LOCAL
&& r
== -ENOMEDIUM
;
42 return log_error_errno(r
,
43 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)" :
44 "Failed to set bus address: %m");
47 int bus_log_connect_error(int r
, BusTransport transport
) {
48 bool hint_vars
= transport
== BUS_TRANSPORT_LOCAL
&& r
== -ENOMEDIUM
,
49 hint_addr
= transport
== BUS_TRANSPORT_LOCAL
&& ERRNO_IS_PRIVILEGE(r
);
51 return log_error_errno(r
,
52 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)" :
53 r
== hint_addr
? "Failed to connect to bus: Operation not permitted (consider using --machine=<user>@.host --user to connect to bus of other user)" :
54 "Failed to connect to 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
,
104 bool exiting
= false;
114 r
= sd_event_get_state(e
);
117 if (r
== SD_EVENT_FINISHED
)
121 idle
= check_idle(userdata
);
125 r
= sd_event_run(e
, exiting
|| !idle
? UINT64_MAX
: timeout
);
129 if (r
== 0 && !exiting
&& idle
) {
130 /* Inform the service manager that we are going down, so that it will queue all
131 * further start requests, instead of assuming we are already running. */
132 sd_notify(false, "STOPPING=1");
134 r
= bus_async_unregister_and_exit(e
, bus
, name
);
142 r
= sd_event_get_exit_code(e
, &code
);
149 int bus_name_has_owner(sd_bus
*c
, const char *name
, sd_bus_error
*error
) {
150 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*rep
= NULL
;
151 int r
, has_owner
= 0;
156 r
= sd_bus_call_method(c
,
157 "org.freedesktop.DBus",
158 "/org/freedesktop/dbus",
159 "org.freedesktop.DBus",
168 r
= sd_bus_message_read_basic(rep
, 'b', &has_owner
);
170 return sd_bus_error_set_errno(error
, r
);
175 bool bus_error_is_unknown_service(const sd_bus_error
*error
) {
176 return sd_bus_error_has_names(error
,
177 SD_BUS_ERROR_SERVICE_UNKNOWN
,
178 SD_BUS_ERROR_NAME_HAS_NO_OWNER
,
179 BUS_ERROR_NO_SUCH_UNIT
);
182 int bus_check_peercred(sd_bus
*c
) {
188 fd
= sd_bus_get_fd(c
);
192 r
= getpeercred(fd
, &ucred
);
196 if (ucred
.uid
!= 0 && ucred
.uid
!= geteuid())
202 int bus_connect_system_systemd(sd_bus
**ret_bus
) {
203 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
209 return sd_bus_default_system(ret_bus
);
211 /* If we are root then let's talk directly to the system
212 * instance, instead of going via the bus */
214 r
= sd_bus_new(&bus
);
218 r
= sd_bus_set_address(bus
, "unix:path=/run/systemd/private");
222 r
= sd_bus_start(bus
);
224 return sd_bus_default_system(ret_bus
);
226 r
= bus_check_peercred(bus
);
230 *ret_bus
= TAKE_PTR(bus
);
234 int bus_connect_user_systemd(sd_bus
**ret_bus
) {
235 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
236 _cleanup_free_
char *ee
= NULL
;
242 e
= secure_getenv("XDG_RUNTIME_DIR");
244 return sd_bus_default_user(ret_bus
);
246 ee
= bus_address_escape(e
);
250 r
= sd_bus_new(&bus
);
254 bus
->address
= strjoin("unix:path=", ee
, "/systemd/private");
258 r
= sd_bus_start(bus
);
260 return sd_bus_default_user(ret_bus
);
262 r
= bus_check_peercred(bus
);
266 *ret_bus
= TAKE_PTR(bus
);
270 int bus_connect_transport(
271 BusTransport transport
,
273 RuntimeScope runtime_scope
,
276 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
279 assert(transport
>= 0);
280 assert(transport
< _BUS_TRANSPORT_MAX
);
283 assert_return((transport
== BUS_TRANSPORT_LOCAL
) == !host
, -EINVAL
);
284 assert_return(transport
!= BUS_TRANSPORT_REMOTE
|| runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
288 case BUS_TRANSPORT_LOCAL
:
290 switch (runtime_scope
) {
292 case RUNTIME_SCOPE_USER
:
293 r
= sd_bus_default_user(&bus
);
296 case RUNTIME_SCOPE_SYSTEM
:
297 if (sd_booted() <= 0)
298 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
299 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
300 "System has not been booted with systemd as init system (PID 1). Can't operate.");
301 r
= sd_bus_default_system(&bus
);
305 assert_not_reached();
309 case BUS_TRANSPORT_REMOTE
:
310 r
= sd_bus_open_system_remote(&bus
, host
);
313 case BUS_TRANSPORT_MACHINE
:
315 switch (runtime_scope
) {
317 case RUNTIME_SCOPE_USER
:
318 r
= sd_bus_open_user_machine(&bus
, host
);
321 case RUNTIME_SCOPE_SYSTEM
:
322 r
= sd_bus_open_system_machine(&bus
, host
);
326 assert_not_reached();
332 assert_not_reached();
337 r
= sd_bus_set_exit_on_disconnect(bus
, true);
341 *ret
= TAKE_PTR(bus
);
345 int bus_connect_transport_systemd(BusTransport transport
, const char *host
, RuntimeScope runtime_scope
, sd_bus
**bus
) {
346 assert(transport
>= 0);
347 assert(transport
< _BUS_TRANSPORT_MAX
);
350 assert_return((transport
== BUS_TRANSPORT_LOCAL
) == !host
, -EINVAL
);
351 assert_return(transport
== BUS_TRANSPORT_LOCAL
|| runtime_scope
== RUNTIME_SCOPE_SYSTEM
, -EOPNOTSUPP
);
355 case BUS_TRANSPORT_LOCAL
:
356 switch (runtime_scope
) {
358 case RUNTIME_SCOPE_USER
:
359 return bus_connect_user_systemd(bus
);
361 case RUNTIME_SCOPE_SYSTEM
:
362 if (sd_booted() <= 0)
363 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
364 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
365 "System has not been booted with systemd as init system (PID 1). Can't operate.");
366 return bus_connect_system_systemd(bus
);
369 assert_not_reached();
374 case BUS_TRANSPORT_REMOTE
:
375 return sd_bus_open_system_remote(bus
, host
);
377 case BUS_TRANSPORT_MACHINE
:
378 return sd_bus_open_system_machine(bus
, host
);
381 assert_not_reached();
386 * bus_path_encode_unique() - encode unique object path
387 * @b: bus connection or NULL
388 * @prefix: object path prefix
389 * @sender_id: unique-name of client, or NULL
390 * @external_id: external ID to be chosen by client, or NULL
391 * @ret_path: storage for encoded object path pointer
393 * Whenever we provide a bus API that allows clients to create and manage
394 * server-side objects, we need to provide a unique name for these objects. If
395 * we let the server choose the name, we suffer from a race condition: If a
396 * client creates an object asynchronously, it cannot destroy that object until
397 * it received the method reply. It cannot know the name of the new object,
398 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
400 * Therefore, many APIs allow the client to choose the unique name for newly
401 * created objects. There're two problems to solve, though:
402 * 1) Object names are usually defined via dbus object paths, which are
403 * usually globally namespaced. Therefore, multiple clients must be able
404 * to choose unique object names without interference.
405 * 2) If multiple libraries share the same bus connection, they must be
406 * able to choose unique object names without interference.
407 * The first problem is solved easily by prefixing a name with the
408 * unique-bus-name of a connection. The server side must enforce this and
409 * reject any other name. The second problem is solved by providing unique
410 * suffixes from within sd-bus.
412 * This helper allows clients to create unique object-paths. It uses the
413 * template '/prefix/sender_id/external_id' and returns the new path in
414 * @ret_path (must be freed by the caller).
415 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
416 * NULL, this function allocates a unique suffix via @b (by requesting a new
417 * cookie). If both @sender_id and @external_id are given, @b can be passed as
420 * Returns: 0 on success, negative error code on failure.
422 int bus_path_encode_unique(sd_bus
*b
, const char *prefix
, const char *sender_id
, const char *external_id
, char **ret_path
) {
423 _cleanup_free_
char *sender_label
= NULL
, *external_label
= NULL
;
424 char external_buf
[DECIMAL_STR_MAX(uint64_t)], *p
;
427 assert_return(b
|| (sender_id
&& external_id
), -EINVAL
);
428 assert_return(sd_bus_object_path_is_valid(prefix
), -EINVAL
);
429 assert_return(ret_path
, -EINVAL
);
432 r
= sd_bus_get_unique_name(b
, &sender_id
);
438 xsprintf(external_buf
, "%"PRIu64
, ++b
->cookie
);
439 external_id
= external_buf
;
442 sender_label
= bus_label_escape(sender_id
);
446 external_label
= bus_label_escape(external_id
);
450 p
= path_join(prefix
, sender_label
, external_label
);
459 * bus_path_decode_unique() - decode unique object path
460 * @path: object path to decode
461 * @prefix: object path prefix
462 * @ret_sender: output parameter for sender-id label
463 * @ret_external: output parameter for external-id label
465 * This does the reverse of bus_path_encode_unique() (see its description for
466 * details). Both trailing labels, sender-id and external-id, are unescaped and
467 * returned in the given output parameters (the caller must free them).
469 * Note that this function returns 0 if the path does not match the template
470 * (see bus_path_encode_unique()), 1 if it matched.
472 * Returns: Negative error code on failure, 0 if the given object path does not
473 * match the template (return parameters are set to NULL), 1 if it was
474 * parsed successfully (return parameters contain allocated labels).
476 int bus_path_decode_unique(const char *path
, const char *prefix
, char **ret_sender
, char **ret_external
) {
478 char *sender
, *external
;
480 assert(sd_bus_object_path_is_valid(path
));
481 assert(sd_bus_object_path_is_valid(prefix
));
483 assert(ret_external
);
485 p
= object_path_startswith(path
, prefix
);
488 *ret_external
= NULL
;
495 *ret_external
= NULL
;
499 sender
= bus_label_unescape_n(p
, q
- p
);
500 external
= bus_label_unescape(q
+ 1);
501 if (!sender
|| !external
) {
507 *ret_sender
= sender
;
508 *ret_external
= external
;
512 int bus_track_add_name_many(sd_bus_track
*t
, char **l
) {
517 /* Continues adding after failure, and returns the first failure. */
522 k
= sd_bus_track_add_name(t
, *i
);
530 int bus_open_system_watch_bind_with_description(sd_bus
**ret
, const char *description
) {
531 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
537 /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal
540 r
= sd_bus_new(&bus
);
545 r
= sd_bus_set_description(bus
, description
);
550 e
= secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
552 e
= DEFAULT_SYSTEM_BUS_ADDRESS
;
554 r
= sd_bus_set_address(bus
, e
);
558 r
= sd_bus_set_bus_client(bus
, true);
562 r
= sd_bus_negotiate_creds(bus
, true, SD_BUS_CREDS_UID
|SD_BUS_CREDS_EUID
|SD_BUS_CREDS_EFFECTIVE_CAPS
);
566 r
= sd_bus_set_watch_bind(bus
, true);
570 r
= sd_bus_set_connected_signal(bus
, true);
574 r
= sd_bus_start(bus
);
578 *ret
= TAKE_PTR(bus
);
583 int bus_reply_pair_array(sd_bus_message
*m
, char **l
) {
584 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
589 /* Reply to the specified message with a message containing a dictionary put together from the
592 r
= sd_bus_message_new_method_return(m
, &reply
);
596 r
= sd_bus_message_open_container(reply
, 'a', "{ss}");
600 STRV_FOREACH_PAIR(k
, v
, l
) {
601 r
= sd_bus_message_append(reply
, "{ss}", *k
, *v
);
606 r
= sd_bus_message_close_container(reply
);
610 return sd_bus_send(NULL
, reply
, NULL
);
613 static int method_dump_memory_state_by_fd(sd_bus_message
*message
, void *userdata
, sd_bus_error
*ret_error
) {
614 _cleanup_(memstream_done
) MemStream m
= {};
615 _cleanup_free_
char *dump
= NULL
;
616 _cleanup_close_
int fd
= -EBADF
;
623 f
= memstream_init(&m
);
627 r
= RET_NERRNO(malloc_info(/* options= */ 0, f
));
631 r
= memstream_finalize(&m
, &dump
, &dump_size
);
635 fd
= acquire_data_fd(dump
, dump_size
, 0);
639 r
= sd_bus_reply_method_return(message
, "h", fd
);
643 return 1; /* Stop further processing */
646 /* The default install callback will fail and disconnect the bus if it cannot register the match, but this
647 * is only a debug method, we definitely don't want to fail in case there's some permission issue. */
648 static int dummy_install_callback(sd_bus_message
*message
, void *userdata
, sd_bus_error
*ret_error
) {
652 int bus_register_malloc_status(sd_bus
*bus
, const char *destination
) {
657 assert(!isempty(destination
));
659 match
= strjoina("type='method_call',"
660 "interface='org.freedesktop.MemoryAllocation1',"
661 "path='/org/freedesktop/MemoryAllocation1',"
662 "destination='", destination
, "',",
663 "member='GetMallocInfo'");
665 r
= sd_bus_add_match_async(bus
, NULL
, match
, method_dump_memory_state_by_fd
, dummy_install_callback
, NULL
);
667 return log_debug_errno(r
, "Failed to subscribe to GetMallocInfo() calls on MemoryAllocation1 interface: %m");
672 static void bus_message_unref_wrapper(void *m
) {
673 sd_bus_message_unref(m
);
676 const struct hash_ops bus_message_hash_ops
= {
677 .hash
= trivial_hash_func
,
678 .compare
= trivial_compare_func
,
679 .free_value
= bus_message_unref_wrapper
,
682 int bus_message_append_string_set(sd_bus_message
*m
, Set
*set
) {
688 r
= sd_bus_message_open_container(m
, 'a', "s");
692 SET_FOREACH(s
, set
) {
693 r
= sd_bus_message_append(m
, "s", s
);
698 return sd_bus_message_close_container(m
);
701 int bus_property_get_string_set(
704 const char *interface
,
705 const char *property
,
706 sd_bus_message
*reply
,
708 sd_bus_error
*error
) {
710 Set
**s
= ASSERT_PTR(userdata
);
716 return bus_message_append_string_set(reply
, *s
);