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 "path-util.h"
22 #include "socket-util.h"
23 #include "stdio-util.h"
25 static int name_owner_change_callback(sd_bus_message
*m
, void *userdata
, sd_bus_error
*ret_error
) {
26 sd_event
*e
= userdata
;
31 sd_bus_close(sd_bus_message_get_bus(m
));
37 int bus_log_address_error(int r
, BusTransport transport
) {
38 bool hint
= transport
== BUS_TRANSPORT_LOCAL
&& r
== -ENOMEDIUM
;
40 return log_error_errno(r
,
41 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)" :
42 "Failed to set bus address: %m");
45 int bus_log_connect_error(int r
, BusTransport transport
) {
46 bool hint_vars
= transport
== BUS_TRANSPORT_LOCAL
&& r
== -ENOMEDIUM
,
47 hint_addr
= transport
== BUS_TRANSPORT_LOCAL
&& ERRNO_IS_PRIVILEGE(r
);
49 return log_error_errno(r
,
50 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)" :
51 r
== hint_addr
? "Failed to connect to bus: Operation not permitted (consider using --machine=<user>@.host --user to connect to bus of other user)" :
52 "Failed to connect to bus: %m");
55 int bus_async_unregister_and_exit(sd_event
*e
, sd_bus
*bus
, const char *name
) {
64 /* We unregister the name here and then wait for the
65 * NameOwnerChanged signal for this event to arrive before we
66 * quit. We do this in order to make sure that any queued
67 * requests are still processed before we really exit. */
69 r
= sd_bus_get_unique_name(bus
, &unique
);
74 "sender='org.freedesktop.DBus',"
76 "interface='org.freedesktop.DBus',"
77 "member='NameOwnerChanged',"
78 "path='/org/freedesktop/DBus',"
80 "arg1='", unique
, "',",
83 r
= sd_bus_add_match_async(bus
, NULL
, match
, name_owner_change_callback
, NULL
, e
);
87 r
= sd_bus_release_name_async(bus
, NULL
, name
, NULL
, NULL
);
94 int bus_event_loop_with_idle(
99 check_idle_t check_idle
,
101 bool exiting
= false;
111 r
= sd_event_get_state(e
);
114 if (r
== SD_EVENT_FINISHED
)
118 idle
= check_idle(userdata
);
122 r
= sd_event_run(e
, exiting
|| !idle
? UINT64_MAX
: timeout
);
126 if (r
== 0 && !exiting
&& idle
) {
127 /* Inform the service manager that we are going down, so that it will queue all
128 * further start requests, instead of assuming we are already running. */
129 sd_notify(false, "STOPPING=1");
131 r
= bus_async_unregister_and_exit(e
, bus
, name
);
140 r
= sd_event_get_exit_code(e
, &code
);
147 int bus_name_has_owner(sd_bus
*c
, const char *name
, sd_bus_error
*error
) {
148 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*rep
= NULL
;
149 int r
, has_owner
= 0;
154 r
= sd_bus_call_method(c
,
155 "org.freedesktop.DBus",
156 "/org/freedesktop/dbus",
157 "org.freedesktop.DBus",
166 r
= sd_bus_message_read_basic(rep
, 'b', &has_owner
);
168 return sd_bus_error_set_errno(error
, r
);
173 bool bus_error_is_unknown_service(const sd_bus_error
*error
) {
174 return sd_bus_error_has_names(error
,
175 SD_BUS_ERROR_SERVICE_UNKNOWN
,
176 SD_BUS_ERROR_NAME_HAS_NO_OWNER
,
177 BUS_ERROR_NO_SUCH_UNIT
);
180 int bus_check_peercred(sd_bus
*c
) {
186 fd
= sd_bus_get_fd(c
);
190 r
= getpeercred(fd
, &ucred
);
194 if (ucred
.uid
!= 0 && ucred
.uid
!= geteuid())
200 int bus_connect_system_systemd(sd_bus
**ret_bus
) {
201 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
207 return sd_bus_default_system(ret_bus
);
209 /* If we are root then let's talk directly to the system
210 * instance, instead of going via the bus */
212 r
= sd_bus_new(&bus
);
216 r
= sd_bus_set_address(bus
, "unix:path=/run/systemd/private");
220 r
= sd_bus_start(bus
);
222 return sd_bus_default_system(ret_bus
);
224 r
= bus_check_peercred(bus
);
228 *ret_bus
= TAKE_PTR(bus
);
232 int bus_connect_user_systemd(sd_bus
**ret_bus
) {
233 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
234 _cleanup_free_
char *ee
= NULL
;
240 e
= secure_getenv("XDG_RUNTIME_DIR");
242 return sd_bus_default_user(ret_bus
);
244 ee
= bus_address_escape(e
);
248 r
= sd_bus_new(&bus
);
252 bus
->address
= strjoin("unix:path=", ee
, "/systemd/private");
256 r
= sd_bus_start(bus
);
258 return sd_bus_default_user(ret_bus
);
260 r
= bus_check_peercred(bus
);
264 *ret_bus
= TAKE_PTR(bus
);
268 int bus_connect_transport(
269 BusTransport transport
,
274 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
277 assert(transport
>= 0);
278 assert(transport
< _BUS_TRANSPORT_MAX
);
281 assert_return((transport
== BUS_TRANSPORT_LOCAL
) == !host
, -EINVAL
);
282 assert_return(transport
!= BUS_TRANSPORT_REMOTE
|| !user
, -EOPNOTSUPP
);
286 case BUS_TRANSPORT_LOCAL
:
288 r
= sd_bus_default_user(&bus
);
290 if (sd_booted() <= 0)
291 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
292 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
293 "System has not been booted with systemd as init system (PID 1). Can't operate.");
294 r
= sd_bus_default_system(&bus
);
298 case BUS_TRANSPORT_REMOTE
:
299 r
= sd_bus_open_system_remote(&bus
, host
);
302 case BUS_TRANSPORT_MACHINE
:
304 r
= sd_bus_open_user_machine(&bus
, host
);
306 r
= sd_bus_open_system_machine(&bus
, host
);
310 assert_not_reached();
315 r
= sd_bus_set_exit_on_disconnect(bus
, true);
319 *ret
= TAKE_PTR(bus
);
323 int bus_connect_transport_systemd(BusTransport transport
, const char *host
, bool user
, sd_bus
**bus
) {
324 assert(transport
>= 0);
325 assert(transport
< _BUS_TRANSPORT_MAX
);
328 assert_return((transport
== BUS_TRANSPORT_LOCAL
) == !host
, -EINVAL
);
329 assert_return(transport
== BUS_TRANSPORT_LOCAL
|| !user
, -EOPNOTSUPP
);
333 case BUS_TRANSPORT_LOCAL
:
335 return bus_connect_user_systemd(bus
);
337 if (sd_booted() <= 0)
338 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
339 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN
),
340 "System has not been booted with systemd as init system (PID 1). Can't operate.");
341 return bus_connect_system_systemd(bus
);
343 case BUS_TRANSPORT_REMOTE
:
344 return sd_bus_open_system_remote(bus
, host
);
346 case BUS_TRANSPORT_MACHINE
:
347 return sd_bus_open_system_machine(bus
, host
);
350 assert_not_reached();
355 * bus_path_encode_unique() - encode unique object path
356 * @b: bus connection or NULL
357 * @prefix: object path prefix
358 * @sender_id: unique-name of client, or NULL
359 * @external_id: external ID to be chosen by client, or NULL
360 * @ret_path: storage for encoded object path pointer
362 * Whenever we provide a bus API that allows clients to create and manage
363 * server-side objects, we need to provide a unique name for these objects. If
364 * we let the server choose the name, we suffer from a race condition: If a
365 * client creates an object asynchronously, it cannot destroy that object until
366 * it received the method reply. It cannot know the name of the new object,
367 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
369 * Therefore, many APIs allow the client to choose the unique name for newly
370 * created objects. There're two problems to solve, though:
371 * 1) Object names are usually defined via dbus object paths, which are
372 * usually globally namespaced. Therefore, multiple clients must be able
373 * to choose unique object names without interference.
374 * 2) If multiple libraries share the same bus connection, they must be
375 * able to choose unique object names without interference.
376 * The first problem is solved easily by prefixing a name with the
377 * unique-bus-name of a connection. The server side must enforce this and
378 * reject any other name. The second problem is solved by providing unique
379 * suffixes from within sd-bus.
381 * This helper allows clients to create unique object-paths. It uses the
382 * template '/prefix/sender_id/external_id' and returns the new path in
383 * @ret_path (must be freed by the caller).
384 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
385 * NULL, this function allocates a unique suffix via @b (by requesting a new
386 * cookie). If both @sender_id and @external_id are given, @b can be passed as
389 * Returns: 0 on success, negative error code on failure.
391 int bus_path_encode_unique(sd_bus
*b
, const char *prefix
, const char *sender_id
, const char *external_id
, char **ret_path
) {
392 _cleanup_free_
char *sender_label
= NULL
, *external_label
= NULL
;
393 char external_buf
[DECIMAL_STR_MAX(uint64_t)], *p
;
396 assert_return(b
|| (sender_id
&& external_id
), -EINVAL
);
397 assert_return(sd_bus_object_path_is_valid(prefix
), -EINVAL
);
398 assert_return(ret_path
, -EINVAL
);
401 r
= sd_bus_get_unique_name(b
, &sender_id
);
407 xsprintf(external_buf
, "%"PRIu64
, ++b
->cookie
);
408 external_id
= external_buf
;
411 sender_label
= bus_label_escape(sender_id
);
415 external_label
= bus_label_escape(external_id
);
419 p
= path_join(prefix
, sender_label
, external_label
);
428 * bus_path_decode_unique() - decode unique object path
429 * @path: object path to decode
430 * @prefix: object path prefix
431 * @ret_sender: output parameter for sender-id label
432 * @ret_external: output parameter for external-id label
434 * This does the reverse of bus_path_encode_unique() (see its description for
435 * details). Both trailing labels, sender-id and external-id, are unescaped and
436 * returned in the given output parameters (the caller must free them).
438 * Note that this function returns 0 if the path does not match the template
439 * (see bus_path_encode_unique()), 1 if it matched.
441 * Returns: Negative error code on failure, 0 if the given object path does not
442 * match the template (return parameters are set to NULL), 1 if it was
443 * parsed successfully (return parameters contain allocated labels).
445 int bus_path_decode_unique(const char *path
, const char *prefix
, char **ret_sender
, char **ret_external
) {
447 char *sender
, *external
;
449 assert(sd_bus_object_path_is_valid(path
));
450 assert(sd_bus_object_path_is_valid(prefix
));
452 assert(ret_external
);
454 p
= object_path_startswith(path
, prefix
);
457 *ret_external
= NULL
;
464 *ret_external
= NULL
;
468 sender
= bus_label_unescape_n(p
, q
- p
);
469 external
= bus_label_unescape(q
+ 1);
470 if (!sender
|| !external
) {
476 *ret_sender
= sender
;
477 *ret_external
= external
;
481 int bus_track_add_name_many(sd_bus_track
*t
, char **l
) {
486 /* Continues adding after failure, and returns the first failure. */
491 k
= sd_bus_track_add_name(t
, *i
);
499 int bus_open_system_watch_bind_with_description(sd_bus
**ret
, const char *description
) {
500 _cleanup_(sd_bus_close_unrefp
) sd_bus
*bus
= NULL
;
506 /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal
509 r
= sd_bus_new(&bus
);
514 r
= sd_bus_set_description(bus
, description
);
519 e
= secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
521 e
= DEFAULT_SYSTEM_BUS_ADDRESS
;
523 r
= sd_bus_set_address(bus
, e
);
527 r
= sd_bus_set_bus_client(bus
, true);
531 r
= sd_bus_negotiate_creds(bus
, true, SD_BUS_CREDS_UID
|SD_BUS_CREDS_EUID
|SD_BUS_CREDS_EFFECTIVE_CAPS
);
535 r
= sd_bus_set_watch_bind(bus
, true);
539 r
= sd_bus_set_connected_signal(bus
, true);
543 r
= sd_bus_start(bus
);
547 *ret
= TAKE_PTR(bus
);
552 int bus_reply_pair_array(sd_bus_message
*m
, char **l
) {
553 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
558 /* Reply to the specified message with a message containing a dictionary put together from the
561 r
= sd_bus_message_new_method_return(m
, &reply
);
565 r
= sd_bus_message_open_container(reply
, 'a', "{ss}");
569 STRV_FOREACH_PAIR(k
, v
, l
) {
570 r
= sd_bus_message_append(reply
, "{ss}", *k
, *v
);
575 r
= sd_bus_message_close_container(reply
);
579 return sd_bus_send(NULL
, reply
, NULL
);
582 static void bus_message_unref_wrapper(void *m
) {
583 sd_bus_message_unref(m
);
586 const struct hash_ops bus_message_hash_ops
= {
587 .hash
= trivial_hash_func
,
588 .compare
= trivial_compare_func
,
589 .free_value
= bus_message_unref_wrapper
,