1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
15 #include "alloc-util.h"
16 #include "bus-container.h"
17 #include "bus-control.h"
18 #include "bus-error.h"
19 #include "bus-internal.h"
20 #include "bus-kernel.h"
21 #include "bus-label.h"
22 #include "bus-message.h"
23 #include "bus-objects.h"
24 #include "bus-protocol.h"
26 #include "bus-socket.h"
27 #include "bus-track.h"
29 #include "cgroup-util.h"
30 #include "errno-util.h"
32 #include "format-util.h"
33 #include "glyph-util.h"
34 #include "hexdecoct.h"
35 #include "hostname-util.h"
38 #include "log-context.h"
39 #include "memory-util.h"
40 #include "origin-id.h"
41 #include "parse-util.h"
42 #include "path-util.h"
44 #include "process-util.h"
46 #include "string-util.h"
48 #include "time-util.h"
49 #include "user-util.h"
51 #define log_debug_bus_message(m) \
53 sd_bus_message *_mm = (m); \
54 log_debug("Got message type=%s sender=%s destination=%s path=%s interface=%s member=%s " \
55 " cookie=%" PRIu64 " reply_cookie=%" PRIu64 \
56 " signature=%s error-name=%s error-message=%s", \
57 strna(bus_message_type_to_string(_mm->header->type)), \
58 strna(sd_bus_message_get_sender(_mm)), \
59 strna(sd_bus_message_get_destination(_mm)), \
60 strna(sd_bus_message_get_path(_mm)), \
61 strna(sd_bus_message_get_interface(_mm)), \
62 strna(sd_bus_message_get_member(_mm)), \
63 BUS_MESSAGE_COOKIE(_mm), \
65 strna(_mm->root_container.signature), \
66 strna(_mm->error.name), \
67 strna(_mm->error.message)); \
70 static int bus_poll(sd_bus
*bus
, bool need_more
, uint64_t timeout_usec
);
71 static void bus_detach_io_events(sd_bus
*b
);
73 static thread_local sd_bus
*default_system_bus
= NULL
;
74 static thread_local sd_bus
*default_user_bus
= NULL
;
75 static thread_local sd_bus
*default_starter_bus
= NULL
;
77 static sd_bus
** bus_choose_default(int (**bus_open
)(sd_bus
**)) {
80 /* Let's try our best to reuse another cached connection. If
81 * the starter bus type is set, connect via our normal
82 * connection logic, ignoring $DBUS_STARTER_ADDRESS, so that
83 * we can share the connection with the user/system default
86 e
= secure_getenv("DBUS_STARTER_BUS_TYPE");
88 if (streq(e
, "system")) {
90 *bus_open
= sd_bus_open_system
;
91 return &default_system_bus
;
92 } else if (STR_IN_SET(e
, "user", "session")) {
94 *bus_open
= sd_bus_open_user
;
95 return &default_user_bus
;
99 /* No type is specified, so we have not other option than to
100 * use the starter address if it is set. */
101 e
= secure_getenv("DBUS_STARTER_ADDRESS");
104 *bus_open
= sd_bus_open
;
105 return &default_starter_bus
;
108 /* Finally, if nothing is set use the cached connection for
111 if (cg_pid_get_owner_uid(0, NULL
) >= 0) {
113 *bus_open
= sd_bus_open_user
;
114 return &default_user_bus
;
117 *bus_open
= sd_bus_open_system
;
118 return &default_system_bus
;
122 sd_bus
*bus_resolve(sd_bus
*bus
) {
123 switch ((uintptr_t) bus
) {
124 case (uintptr_t) SD_BUS_DEFAULT
:
125 return *(bus_choose_default(NULL
));
126 case (uintptr_t) SD_BUS_DEFAULT_USER
:
127 return default_user_bus
;
128 case (uintptr_t) SD_BUS_DEFAULT_SYSTEM
:
129 return default_system_bus
;
135 void bus_close_io_fds(sd_bus
*b
) {
138 bus_detach_io_events(b
);
140 if (b
->input_fd
!= b
->output_fd
)
141 safe_close(b
->output_fd
);
142 b
->output_fd
= b
->input_fd
= safe_close(b
->input_fd
);
145 void bus_close_inotify_fd(sd_bus
*b
) {
148 b
->inotify_event_source
= sd_event_source_disable_unref(b
->inotify_event_source
);
150 b
->inotify_fd
= safe_close(b
->inotify_fd
);
151 b
->inotify_watches
= mfree(b
->inotify_watches
);
152 b
->n_inotify_watches
= 0;
155 static void bus_close_fds(sd_bus
*b
) {
159 bus_close_inotify_fd(b
);
160 b
->pidfd
= safe_close(b
->pidfd
);
163 static void bus_reset_queues(sd_bus
*b
) {
166 while (b
->rqueue_size
> 0)
167 bus_message_unref_queued(b
->rqueue
[--b
->rqueue_size
], b
);
169 b
->rqueue
= mfree(b
->rqueue
);
171 while (b
->wqueue_size
> 0)
172 bus_message_unref_queued(b
->wqueue
[--b
->wqueue_size
], b
);
174 b
->wqueue
= mfree(b
->wqueue
);
177 static sd_bus
* bus_free(sd_bus
*b
) {
181 assert(!b
->track_queue
);
184 b
->state
= BUS_CLOSED
;
186 sd_bus_detach_event(b
);
188 while ((s
= b
->slots
)) {
189 /* At this point only floating slots can still be
190 * around, because the non-floating ones keep a
191 * reference to the bus, and we thus couldn't be
192 * destructing right now... We forcibly disconnect the
193 * slots here, so that they still can be referenced by
194 * apps, but are dead. */
197 bus_slot_disconnect(s
, true);
200 if (b
->default_bus_ptr
)
201 *b
->default_bus_ptr
= NULL
;
208 free(b
->unique_name
);
209 free(b
->auth_buffer
);
212 free(b
->description
);
213 free(b
->patch_sender
);
216 strv_free(b
->exec_argv
);
218 close_many(b
->fds
, b
->n_fds
);
223 ordered_hashmap_free(b
->reply_callbacks
);
224 prioq_free(b
->reply_callbacks_prioq
);
226 assert(b
->match_callbacks
.type
== BUS_MATCH_ROOT
);
227 bus_match_free(&b
->match_callbacks
);
229 set_free(b
->vtable_methods
);
230 set_free(b
->vtable_properties
);
232 assert(hashmap_isempty(b
->nodes
));
233 hashmap_free(b
->nodes
);
237 assert_se(pthread_mutex_destroy(&b
->memfd_cache_mutex
) == 0);
242 DEFINE_TRIVIAL_CLEANUP_FUNC(sd_bus
*, bus_free
);
244 DEFINE_ORIGIN_ID_HELPERS(sd_bus
, bus
);
246 _public_
int sd_bus_new(sd_bus
**ret
) {
247 _cleanup_free_ sd_bus
*b
= NULL
;
249 assert_return(ret
, -EINVAL
);
259 .inotify_fd
= -EBADF
,
260 .message_version
= 1,
261 .creds_mask
= SD_BUS_CREDS_WELL_KNOWN_NAMES
|SD_BUS_CREDS_UNIQUE_NAME
,
263 .origin_id
= origin_id_query(),
264 .n_groups
= SIZE_MAX
,
265 .close_on_exit
= true,
266 .ucred
= UCRED_INVALID
,
268 .runtime_scope
= _RUNTIME_SCOPE_INVALID
,
269 .connect_as_uid
= UID_INVALID
,
270 .connect_as_gid
= GID_INVALID
,
273 /* We guarantee that wqueue always has space for at least one entry */
274 if (!GREEDY_REALLOC(b
->wqueue
, 1))
277 assert_se(pthread_mutex_init(&b
->memfd_cache_mutex
, NULL
) == 0);
283 _public_
int sd_bus_set_address(sd_bus
*bus
, const char *address
) {
284 assert_return(bus
, -EINVAL
);
285 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
286 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
287 assert_return(address
, -EINVAL
);
288 assert_return(!bus_origin_changed(bus
), -ECHILD
);
290 return free_and_strdup(&bus
->address
, address
);
293 _public_
int sd_bus_set_fd(sd_bus
*bus
, int input_fd
, int output_fd
) {
294 assert_return(bus
, -EINVAL
);
295 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
296 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
297 assert_return(input_fd
>= 0, -EBADF
);
298 assert_return(output_fd
>= 0, -EBADF
);
299 assert_return(!bus_origin_changed(bus
), -ECHILD
);
301 bus
->input_fd
= input_fd
;
302 bus
->output_fd
= output_fd
;
306 _public_
int sd_bus_set_exec(sd_bus
*bus
, const char *path
, char *const *argv
) {
307 _cleanup_strv_free_
char **a
= NULL
;
310 assert_return(bus
, -EINVAL
);
311 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
312 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
313 assert_return(path
, -EINVAL
);
314 assert_return(!strv_isempty(argv
), -EINVAL
);
315 assert_return(!bus_origin_changed(bus
), -ECHILD
);
321 r
= free_and_strdup(&bus
->exec_path
, path
);
325 return strv_free_and_replace(bus
->exec_argv
, a
);
328 _public_
int sd_bus_set_bus_client(sd_bus
*bus
, int b
) {
329 assert_return(bus
, -EINVAL
);
330 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
331 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
332 assert_return(!bus
->patch_sender
, -EPERM
);
333 assert_return(!bus_origin_changed(bus
), -ECHILD
);
339 _public_
int sd_bus_set_monitor(sd_bus
*bus
, int b
) {
340 assert_return(bus
, -EINVAL
);
341 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
342 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
343 assert_return(!bus_origin_changed(bus
), -ECHILD
);
349 _public_
int sd_bus_negotiate_fds(sd_bus
*bus
, int b
) {
350 assert_return(bus
, -EINVAL
);
351 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
352 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
353 assert_return(!bus_origin_changed(bus
), -ECHILD
);
359 _public_
int sd_bus_negotiate_timestamp(sd_bus
*bus
, int b
) {
360 assert_return(bus
, -EINVAL
);
361 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
362 assert_return(!IN_SET(bus
->state
, BUS_CLOSING
, BUS_CLOSED
), -EPERM
);
363 assert_return(!bus_origin_changed(bus
), -ECHILD
);
365 /* This is not actually supported by any of our transports these days, but we do honour it for synthetic
366 * replies, and maybe one day classic D-Bus learns this too */
367 bus
->attach_timestamp
= b
;
372 _public_
int sd_bus_negotiate_creds(sd_bus
*bus
, int b
, uint64_t mask
) {
373 assert_return(bus
, -EINVAL
);
374 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
375 assert_return(mask
<= _SD_BUS_CREDS_ALL
, -EINVAL
);
376 assert_return(!IN_SET(bus
->state
, BUS_CLOSING
, BUS_CLOSED
), -EPERM
);
377 assert_return(!bus_origin_changed(bus
), -ECHILD
);
379 SET_FLAG(bus
->creds_mask
, mask
, b
);
381 /* The well knowns we need unconditionally, so that matches can work */
382 bus
->creds_mask
|= SD_BUS_CREDS_WELL_KNOWN_NAMES
|SD_BUS_CREDS_UNIQUE_NAME
;
387 _public_
int sd_bus_set_server(sd_bus
*bus
, int b
, sd_id128_t server_id
) {
388 assert_return(bus
, -EINVAL
);
389 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
390 assert_return(b
|| sd_id128_equal(server_id
, SD_ID128_NULL
), -EINVAL
);
391 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
392 assert_return(!bus_origin_changed(bus
), -ECHILD
);
395 bus
->server_id
= server_id
;
399 _public_
int sd_bus_set_anonymous(sd_bus
*bus
, int b
) {
400 assert_return(bus
, -EINVAL
);
401 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
402 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
403 assert_return(!bus_origin_changed(bus
), -ECHILD
);
405 bus
->anonymous_auth
= b
;
409 _public_
int sd_bus_set_trusted(sd_bus
*bus
, int b
) {
410 assert_return(bus
, -EINVAL
);
411 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
412 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
413 assert_return(!bus_origin_changed(bus
), -ECHILD
);
419 _public_
int sd_bus_set_description(sd_bus
*bus
, const char *description
) {
420 assert_return(bus
, -EINVAL
);
421 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
422 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
423 assert_return(!bus_origin_changed(bus
), -ECHILD
);
425 return free_and_strdup(&bus
->description
, description
);
428 _public_
int sd_bus_set_allow_interactive_authorization(sd_bus
*bus
, int b
) {
429 assert_return(bus
, -EINVAL
);
430 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
431 assert_return(!bus_origin_changed(bus
), -ECHILD
);
433 bus
->allow_interactive_authorization
= b
;
437 _public_
int sd_bus_get_allow_interactive_authorization(sd_bus
*bus
) {
438 assert_return(bus
, -EINVAL
);
439 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
440 assert_return(!bus_origin_changed(bus
), -ECHILD
);
442 return bus
->allow_interactive_authorization
;
445 _public_
int sd_bus_set_watch_bind(sd_bus
*bus
, int b
) {
446 assert_return(bus
, -EINVAL
);
447 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
448 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
449 assert_return(!bus_origin_changed(bus
), -ECHILD
);
455 _public_
int sd_bus_get_watch_bind(sd_bus
*bus
) {
456 assert_return(bus
, -EINVAL
);
457 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
458 assert_return(!bus_origin_changed(bus
), -ECHILD
);
460 return bus
->watch_bind
;
463 _public_
int sd_bus_set_connected_signal(sd_bus
*bus
, int b
) {
464 assert_return(bus
, -EINVAL
);
465 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
466 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
467 assert_return(!bus_origin_changed(bus
), -ECHILD
);
469 bus
->connected_signal
= b
;
473 _public_
int sd_bus_get_connected_signal(sd_bus
*bus
) {
474 assert_return(bus
, -EINVAL
);
475 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
476 assert_return(!bus_origin_changed(bus
), -ECHILD
);
478 return bus
->connected_signal
;
481 static int synthesize_connected_signal(sd_bus
*bus
) {
482 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
487 /* If enabled, synthesizes a local "Connected" signal mirroring the local "Disconnected" signal. This is called
488 * whenever we fully established a connection, i.e. after the authorization phase, and after receiving the
489 * Hello() reply. Or in other words, whenever we enter BUS_RUNNING state.
491 * This is useful so that clients can start doing stuff whenever the connection is fully established in a way
492 * that works independently from whether we connected to a full bus or just a direct connection. */
494 if (!bus
->connected_signal
)
497 r
= sd_bus_message_new_signal(
500 "/org/freedesktop/DBus/Local",
501 "org.freedesktop.DBus.Local",
506 bus_message_set_sender_local(bus
, m
);
507 m
->read_counter
= ++bus
->read_counter
;
509 r
= bus_seal_synthetic_message(bus
, m
);
513 r
= bus_rqueue_make_room(bus
);
517 /* Insert at the very front */
518 memmove(bus
->rqueue
+ 1, bus
->rqueue
, sizeof(sd_bus_message
*) * bus
->rqueue_size
);
519 bus
->rqueue
[0] = bus_message_ref_queued(m
, bus
);
525 void bus_set_state(sd_bus
*bus
, BusState state
) {
526 static const char* const table
[_BUS_STATE_MAX
] = {
527 [BUS_UNSET
] = "UNSET",
528 [BUS_WATCH_BIND
] = "WATCH_BIND",
529 [BUS_OPENING
] = "OPENING",
530 [BUS_AUTHENTICATING
] = "AUTHENTICATING",
531 [BUS_HELLO
] = "HELLO",
532 [BUS_RUNNING
] = "RUNNING",
533 [BUS_CLOSING
] = "CLOSING",
534 [BUS_CLOSED
] = "CLOSED",
538 assert(state
< _BUS_STATE_MAX
);
540 if (state
== bus
->state
)
543 log_debug("Bus %s: changing state %s %s %s", strna(bus
->description
),
544 table
[bus
->state
], glyph(GLYPH_ARROW_RIGHT
), table
[state
]);
548 static int hello_callback(sd_bus_message
*reply
, void *userdata
, sd_bus_error
*reterr_error
) {
556 assert(IN_SET(bus
->state
, BUS_HELLO
, BUS_CLOSING
));
558 r
= sd_bus_message_get_errno(reply
);
564 r
= sd_bus_message_read(reply
, "s", &s
);
568 if (!service_name_is_valid(s
) || s
[0] != ':') {
573 r
= free_and_strdup(&bus
->unique_name
, s
);
577 if (bus
->state
== BUS_HELLO
) {
578 bus_set_state(bus
, BUS_RUNNING
);
580 r
= synthesize_connected_signal(bus
);
588 /* When Hello() failed, let's propagate this in two ways: first we return the error immediately here,
589 * which is the propagated up towards the event loop. Let's also invalidate the connection, so that
590 * if the user then calls back into us again we won't wait any longer. */
592 bus_set_state(bus
, BUS_CLOSING
);
596 static int bus_send_hello(sd_bus
*bus
) {
597 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
602 if (!bus
->bus_client
)
605 r
= sd_bus_message_new_method_call(
608 "org.freedesktop.DBus",
609 "/org/freedesktop/DBus",
610 "org.freedesktop.DBus",
615 return sd_bus_call_async(bus
, NULL
, m
, hello_callback
, NULL
, 0);
618 int bus_start_running(sd_bus
*bus
) {
624 assert(bus
->state
< BUS_HELLO
);
626 /* We start all method call timeouts when we enter BUS_HELLO or BUS_RUNNING mode. At this point let's convert
627 * all relative to absolute timestamps. Note that we do not reshuffle the reply callback priority queue since
628 * adding a fixed value to all entries should not alter the internal order. */
630 n
= now(CLOCK_MONOTONIC
);
631 ORDERED_HASHMAP_FOREACH(c
, bus
->reply_callbacks
) {
632 if (c
->timeout_usec
== 0)
635 c
->timeout_usec
= usec_add(n
, c
->timeout_usec
);
638 if (bus
->bus_client
) {
639 bus_set_state(bus
, BUS_HELLO
);
643 bus_set_state(bus
, BUS_RUNNING
);
645 r
= synthesize_connected_signal(bus
);
652 static int parse_address_key(const char **p
, const char *key
, char **value
) {
653 _cleanup_free_
char *r
= NULL
;
662 a
= startswith(*p
, key
);
673 while (!IN_SET(*a
, ';', ',', 0)) {
687 c
= (char) ((x
<< 4) | y
);
694 if (!GREEDY_REALLOC(r
, n
+ 2))
712 free_and_replace(*value
, r
);
717 static void skip_address_key(const char **p
) {
721 *p
+= strcspn(*p
, ",");
727 static int parse_unix_address(sd_bus
*b
, const char **p
, char **guid
) {
728 _cleanup_free_
char *path
= NULL
, *abstract
= NULL
, *uids
= NULL
, *gids
= NULL
;
737 while (!IN_SET(**p
, 0, ';')) {
738 r
= parse_address_key(p
, "guid", guid
);
744 r
= parse_address_key(p
, "path", &path
);
750 r
= parse_address_key(p
, "abstract", &abstract
);
756 r
= parse_address_key(p
, "uid", &uids
);
762 r
= parse_address_key(p
, "gid", &gids
);
771 if (!path
&& !abstract
)
774 if (path
&& abstract
)
779 if (l
>= sizeof(b
->sockaddr
.un
.sun_path
)) /* We insist on NUL termination */
782 b
->sockaddr
.un
= (struct sockaddr_un
) {
783 .sun_family
= AF_UNIX
,
786 memcpy(b
->sockaddr
.un
.sun_path
, path
, l
);
787 b
->sockaddr_size
= offsetof(struct sockaddr_un
, sun_path
) + l
+ 1;
792 l
= strlen(abstract
);
793 if (l
>= sizeof(b
->sockaddr
.un
.sun_path
) - 1) /* We insist on NUL termination */
796 b
->sockaddr
.un
= (struct sockaddr_un
) {
797 .sun_family
= AF_UNIX
,
800 memcpy(b
->sockaddr
.un
.sun_path
+1, abstract
, l
);
801 b
->sockaddr_size
= offsetof(struct sockaddr_un
, sun_path
) + 1 + l
;
805 r
= parse_uid(uids
, &b
->connect_as_uid
);
810 r
= parse_gid(gids
, &b
->connect_as_gid
);
820 static int parse_tcp_address(sd_bus
*b
, const char **p
, char **guid
) {
821 _cleanup_free_
char *host
= NULL
, *port
= NULL
, *family
= NULL
;
823 struct addrinfo
*result
, hints
= {
824 .ai_socktype
= SOCK_STREAM
,
832 while (!IN_SET(**p
, 0, ';')) {
833 r
= parse_address_key(p
, "guid", guid
);
839 r
= parse_address_key(p
, "host", &host
);
845 r
= parse_address_key(p
, "port", &port
);
851 r
= parse_address_key(p
, "family", &family
);
864 hints
.ai_family
= af_from_ipv4_ipv6(family
);
865 if (hints
.ai_family
== AF_UNSPEC
)
869 r
= getaddrinfo(host
, port
, &hints
, &result
);
873 return -EADDRNOTAVAIL
;
875 memcpy(&b
->sockaddr
, result
->ai_addr
, result
->ai_addrlen
);
876 b
->sockaddr_size
= result
->ai_addrlen
;
878 freeaddrinfo(result
);
885 static int parse_exec_address(sd_bus
*b
, const char **p
, char **guid
) {
887 unsigned n_argv
= 0, j
;
896 while (!IN_SET(**p
, 0, ';')) {
897 r
= parse_address_key(p
, "guid", guid
);
903 r
= parse_address_key(p
, "path", &path
);
909 if (startswith(*p
, "argv")) {
913 ul
= strtoul(*p
+ 4, (char**) p
, 10);
914 if (errno
> 0 || **p
!= '=' || ul
> 256) {
922 if (!GREEDY_REALLOC0(argv
, ul
+ 2)) {
930 r
= parse_address_key(p
, NULL
, argv
+ ul
);
945 /* Make sure there are no holes in the array, with the
946 * exception of argv[0] */
947 for (j
= 1; j
< n_argv
; j
++)
953 if (argv
&& argv
[0] == NULL
) {
954 argv
[0] = strdup(path
);
969 for (j
= 0; j
< n_argv
; j
++)
977 static int parse_container_unix_address(sd_bus
*b
, const char **p
, char **guid
) {
978 _cleanup_free_
char *machine
= NULL
, *pid
= NULL
;
986 while (!IN_SET(**p
, 0, ';')) {
987 r
= parse_address_key(p
, "guid", guid
);
993 r
= parse_address_key(p
, "machine", &machine
);
999 r
= parse_address_key(p
, "pid", &pid
);
1005 skip_address_key(p
);
1008 if (!machine
== !pid
)
1012 if (!hostname_is_valid(machine
, VALID_HOSTNAME_DOT_HOST
))
1015 free_and_replace(b
->machine
, machine
);
1017 b
->machine
= mfree(b
->machine
);
1020 r
= parse_pid(pid
, &b
->nspid
);
1026 b
->sockaddr
.un
= (struct sockaddr_un
) {
1027 .sun_family
= AF_UNIX
,
1028 /* Note that we use the old /var/run prefix here, to increase compatibility with really old containers */
1029 .sun_path
= "/var/run/dbus/system_bus_socket",
1031 b
->sockaddr_size
= sockaddr_un_len(&b
->sockaddr
.un
);
1032 b
->is_local
= false;
1037 static void bus_reset_parsed_address(sd_bus
*b
) {
1041 b
->sockaddr_size
= 0;
1042 b
->exec_argv
= strv_free(b
->exec_argv
);
1043 b
->exec_path
= mfree(b
->exec_path
);
1044 b
->server_id
= SD_ID128_NULL
;
1045 b
->machine
= mfree(b
->machine
);
1049 static int bus_parse_next_address(sd_bus
*b
) {
1050 _cleanup_free_
char *guid
= NULL
;
1058 if (b
->address
[b
->address_index
] == 0)
1061 bus_reset_parsed_address(b
);
1063 a
= b
->address
+ b
->address_index
;
1072 if (startswith(a
, "unix:")) {
1075 r
= parse_unix_address(b
, &a
, &guid
);
1080 } else if (startswith(a
, "tcp:")) {
1083 r
= parse_tcp_address(b
, &a
, &guid
);
1089 } else if (startswith(a
, "unixexec:")) {
1092 r
= parse_exec_address(b
, &a
, &guid
);
1098 } else if (startswith(a
, "x-machine-unix:")) {
1101 r
= parse_container_unix_address(b
, &a
, &guid
);
1114 r
= sd_id128_from_string(guid
, &b
->server_id
);
1119 b
->address_index
= a
- b
->address
;
1123 static void bus_kill_exec(sd_bus
*bus
) {
1124 if (!pid_is_valid(bus
->busexec_pid
))
1127 sigterm_wait(TAKE_PID(bus
->busexec_pid
));
1130 static int bus_start_address(sd_bus
*b
) {
1140 /* If you provide multiple different bus-addresses, we
1141 * try all of them in order and use the first one that
1145 r
= bus_socket_exec(b
);
1146 else if ((b
->nspid
> 0 || b
->machine
) && b
->sockaddr
.sa
.sa_family
!= AF_UNSPEC
)
1147 r
= bus_container_connect_socket(b
);
1148 else if (b
->sockaddr
.sa
.sa_family
!= AF_UNSPEC
)
1149 r
= bus_socket_connect(b
);
1156 q
= bus_attach_io_events(b
);
1160 q
= bus_attach_inotify_event(b
);
1167 b
->last_connect_error
= -r
;
1170 r
= bus_parse_next_address(b
);
1174 return b
->last_connect_error
> 0 ? -b
->last_connect_error
: -ECONNREFUSED
;
1178 int bus_next_address(sd_bus
*b
) {
1181 bus_reset_parsed_address(b
);
1182 return bus_start_address(b
);
1185 static int bus_start_fd(sd_bus
*b
) {
1190 assert(b
->input_fd
>= 0);
1191 assert(b
->output_fd
>= 0);
1193 if (DEBUG_LOGGING
) {
1194 _cleanup_free_
char *pi
= NULL
, *po
= NULL
;
1195 (void) fd_get_path(b
->input_fd
, &pi
);
1196 (void) fd_get_path(b
->output_fd
, &po
);
1197 log_debug("sd-bus: starting bus%s%s on fds %d/%d (%s, %s)...",
1198 b
->description
? " " : "", strempty(b
->description
),
1199 b
->input_fd
, b
->output_fd
,
1200 pi
?: "???", po
?: "???");
1203 r
= fd_nonblock(b
->input_fd
, true);
1207 r
= fd_cloexec(b
->input_fd
, true);
1211 if (b
->input_fd
!= b
->output_fd
) {
1212 r
= fd_nonblock(b
->output_fd
, true);
1216 r
= fd_cloexec(b
->output_fd
, true);
1221 if (fstat(b
->input_fd
, &st
) < 0)
1224 return bus_socket_take_fd(b
);
1227 _public_
int sd_bus_start(sd_bus
*bus
) {
1230 assert_return(bus
, -EINVAL
);
1231 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
1232 assert_return(bus
->state
== BUS_UNSET
, -EPERM
);
1233 assert_return(!bus_origin_changed(bus
), -ECHILD
);
1235 bus_set_state(bus
, BUS_OPENING
);
1237 if (bus
->is_server
&& bus
->bus_client
)
1240 if (bus
->input_fd
>= 0)
1241 r
= bus_start_fd(bus
);
1242 else if (bus
->address
|| bus
->sockaddr
.sa
.sa_family
!= AF_UNSPEC
|| bus
->exec_path
|| bus
->machine
)
1243 r
= bus_start_address(bus
);
1252 return bus_send_hello(bus
);
1255 _public_
int sd_bus_open_with_description(sd_bus
**ret
, const char *description
) {
1257 _cleanup_(bus_freep
) sd_bus
*b
= NULL
;
1260 assert_return(ret
, -EINVAL
);
1262 /* Let's connect to the starter bus if it is set, and
1263 * otherwise to the bus that is appropriate for the scope
1264 * we are running in */
1266 e
= secure_getenv("DBUS_STARTER_BUS_TYPE");
1268 if (streq(e
, "system"))
1269 return sd_bus_open_system_with_description(ret
, description
);
1270 if (STR_IN_SET(e
, "session", "user"))
1271 return sd_bus_open_user_with_description(ret
, description
);
1274 e
= secure_getenv("DBUS_STARTER_ADDRESS");
1276 if (cg_pid_get_owner_uid(0, NULL
) >= 0)
1277 return sd_bus_open_user_with_description(ret
, description
);
1279 return sd_bus_open_system_with_description(ret
, description
);
1286 r
= sd_bus_set_address(b
, e
);
1290 b
->bus_client
= true;
1292 /* We don't know whether the bus is trusted or not, so better
1293 * be safe, and authenticate everything */
1295 b
->is_local
= false;
1296 b
->creds_mask
|= SD_BUS_CREDS_UID
| SD_BUS_CREDS_EUID
| SD_BUS_CREDS_EFFECTIVE_CAPS
;
1298 r
= sd_bus_start(b
);
1306 _public_
int sd_bus_open(sd_bus
**ret
) {
1307 return sd_bus_open_with_description(ret
, NULL
);
1310 int bus_set_address_system(sd_bus
*b
) {
1316 e
= secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1318 r
= sd_bus_set_address(b
, e
?: DEFAULT_SYSTEM_BUS_ADDRESS
);
1322 b
->runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
1326 _public_
int sd_bus_open_system_with_description(sd_bus
**ret
, const char *description
) {
1327 _cleanup_(bus_freep
) sd_bus
*b
= NULL
;
1330 assert_return(ret
, -EINVAL
);
1337 r
= sd_bus_set_description(b
, description
);
1342 r
= bus_set_address_system(b
);
1346 b
->bus_client
= true;
1348 /* Let's do per-method access control on the system bus. We
1349 * need the caller's UID and capability set for that. */
1351 b
->creds_mask
|= SD_BUS_CREDS_UID
| SD_BUS_CREDS_EUID
| SD_BUS_CREDS_EFFECTIVE_CAPS
;
1354 r
= sd_bus_start(b
);
1362 _public_
int sd_bus_open_system(sd_bus
**ret
) {
1363 return sd_bus_open_system_with_description(ret
, NULL
);
1366 int bus_set_address_user(sd_bus
*b
) {
1368 _cleanup_free_
char *_a
= NULL
;
1373 a
= secure_getenv("DBUS_SESSION_BUS_ADDRESS");
1376 _cleanup_free_
char *ee
= NULL
;
1378 e
= secure_getenv("XDG_RUNTIME_DIR");
1380 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
1381 "sd-bus: $XDG_RUNTIME_DIR not set, cannot connect to user bus.");
1383 ee
= bus_address_escape(e
);
1387 if (asprintf(&_a
, DEFAULT_USER_BUS_ADDRESS_FMT
, ee
) < 0)
1392 r
= sd_bus_set_address(b
, a
);
1396 b
->runtime_scope
= RUNTIME_SCOPE_USER
;
1400 _public_
int sd_bus_open_user_with_description(sd_bus
**ret
, const char *description
) {
1401 _cleanup_(bus_freep
) sd_bus
*b
= NULL
;
1404 assert_return(ret
, -EINVAL
);
1411 r
= sd_bus_set_description(b
, description
);
1416 r
= bus_set_address_user(b
);
1420 b
->bus_client
= true;
1422 /* We don't do any per-method access control on the user bus. */
1426 r
= sd_bus_start(b
);
1434 _public_
int sd_bus_open_user(sd_bus
**ret
) {
1435 return sd_bus_open_user_with_description(ret
, NULL
);
1438 int bus_set_address_system_remote(sd_bus
*b
, const char *host
) {
1439 _cleanup_free_
char *e
= NULL
;
1440 char *m
= NULL
, *c
= NULL
, *a
, *rbracket
= NULL
, *p
= NULL
;
1445 /* Skip ":"s in ipv6 addresses */
1449 rbracket
= strchr(host
, ']');
1452 t
= strndupa_safe(host
+ 1, rbracket
- host
- 1);
1453 e
= bus_address_escape(t
);
1456 } else if ((a
= strchr(host
, '@'))) {
1457 if (*(a
+ 1) == '[') {
1458 _cleanup_free_
char *t
= NULL
;
1460 rbracket
= strchr(a
+ 1, ']');
1463 t
= new0(char, strlen(host
));
1466 strncat(t
, host
, a
- host
+ 1);
1467 strncat(t
, a
+ 2, rbracket
- a
- 2);
1468 e
= bus_address_escape(t
);
1471 } else if (*(a
+ 1) == '\0' || strchr(a
+ 1, '@'))
1475 /* Let's see if a port was given */
1476 m
= strchr(rbracket
? rbracket
+ 1 : host
, ':');
1479 bool got_forward_slash
= false;
1485 p
= strndupa_safe(p
, t
- p
);
1486 got_forward_slash
= true;
1489 if (!in_charset(p
, "0123456789") || *p
== '\0') {
1490 if (!hostname_is_valid(p
, 0) || got_forward_slash
)
1494 goto interpret_port_as_machine_old_syntax
;
1498 /* Let's see if a machine was given */
1499 m
= strchr(rbracket
? rbracket
+ 1 : host
, '/');
1502 interpret_port_as_machine_old_syntax
:
1503 /* Let's make sure this is not a port of some kind,
1504 * and is a valid machine name. */
1505 if (!in_charset(m
, "0123456789") && hostname_is_valid(m
, 0))
1506 c
= strjoina(",argv", p
? "7" : "5", "=--machine=", m
);
1512 t
= strndupa_safe(host
, strcspn(host
, ":/"));
1514 e
= bus_address_escape(t
);
1519 const char *ssh
= secure_getenv("SYSTEMD_SSH") ?: "ssh";
1520 _cleanup_free_
char *ssh_escaped
= bus_address_escape(ssh
);
1524 a
= strjoin("unixexec:path=", ssh_escaped
, ",argv1=-xT",
1525 p
? ",argv2=-p,argv3=" : "", strempty(p
),
1526 ",argv", p
? "4" : "2", "=--,argv", p
? "5" : "3", "=", e
,
1527 ",argv", p
? "6" : "4", "=systemd-stdio-bridge", c
);
1531 return free_and_replace(b
->address
, a
);
1534 _public_
int sd_bus_open_system_remote(sd_bus
**ret
, const char *host
) {
1535 _cleanup_(bus_freep
) sd_bus
*b
= NULL
;
1538 assert_return(host
, -EINVAL
);
1539 assert_return(ret
, -EINVAL
);
1545 r
= bus_set_address_system_remote(b
, host
);
1549 b
->bus_client
= true;
1551 b
->runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
1552 b
->is_local
= false;
1554 r
= sd_bus_start(b
);
1562 int bus_set_address_machine(sd_bus
*b
, RuntimeScope runtime_scope
, const char *machine
) {
1563 _cleanup_free_
char *a
= NULL
;
1566 assert(IN_SET(runtime_scope
, RUNTIME_SCOPE_SYSTEM
, RUNTIME_SCOPE_USER
));
1569 _cleanup_free_
char *u
= NULL
, *h
= NULL
;
1571 with_at
= split_user_at_host(machine
, &u
, &h
);
1575 if (with_at
|| runtime_scope
== RUNTIME_SCOPE_USER
) {
1576 _cleanup_free_
char *eu
= NULL
, *eh
= NULL
;
1578 /* If there's an "@" in the container specification, we'll connect as a user specified at its
1579 * left hand side, which is useful in combination with user=true. This isn't as trivial as it
1580 * might sound: it's not sufficient to enter the container and connect to some socket there,
1581 * since the --user socket path depends on $XDG_RUNTIME_DIR which is set via PAM. Thus, to be
1582 * able to connect, we need to have a PAM session. Our way out? We use systemd-run to get
1583 * into the container and acquire a PAM session there, and then invoke systemd-stdio-bridge
1584 * in it, which propagates the bus transport to us. */
1588 u
= getusername_malloc(); /* Empty user name, let's use the local one */
1593 eu
= bus_address_escape(u
);
1598 /* No "@" specified but we shall connect to the user instance? Then assume root (and
1599 * not a user named identically to the calling one). This means:
1601 * --machine=foobar --user → connect to user bus of root user in container "foobar"
1602 * --machine=@foobar --user → connect to user bus of user named like the calling user in container "foobar"
1604 * Why? so that behaviour for "--machine=foobar --system" is roughly similar to
1605 * "--machine=foobar --user": both times we unconditionally connect as root user
1606 * regardless what the calling user is. */
1609 eh
= bus_address_escape(h
);
1614 /* systemd-run -M… -PGq --wait -pUser=… -pPAMName=login systemd-stdio-bridge */
1616 a
= strjoin("unixexec:path=systemd-run,"
1617 "argv1=-M", eh
?: ".host", ","
1620 "argv4=-pUser%3d", eu
?: "root", ",",
1621 "argv5=-pPAMName%3dlogin,"
1622 "argv6=systemd-stdio-bridge");
1626 if (runtime_scope
== RUNTIME_SCOPE_USER
) {
1627 /* Ideally we'd use the "--user" switch to systemd-stdio-bridge here, but it's only
1628 * available in recent systemd versions. Using the "-p" switch with the explicit path
1629 * is a working alternative, and is compatible with older versions, hence that's what
1631 if (!strextend(&a
, ",argv7=-punix:path%3d%24%7bXDG_RUNTIME_DIR%7d/bus"))
1635 _cleanup_free_
char *e
= NULL
;
1637 /* Just a container name, we can go the simple way, and just join the container, and connect
1638 * to the well-known path of the system bus there. */
1640 e
= bus_address_escape(h
?: ".host");
1644 a
= strjoin("x-machine-unix:machine=", e
);
1649 return free_and_replace(b
->address
, a
);
1652 static int machine_spec_is_current_identity(const char *user_and_machine
) {
1653 /* Returns true if the specified user+machine name are actually equivalent to our own identity and
1654 * our own host. If so we can shortcut things. Why bother? Because that way we don't have to fork
1655 * off short-lived worker processes that are then unavailable for authentication and logging in the
1656 * peer. Moreover joining a namespace requires privileges. If we are in the right namespace anyway,
1657 * we can avoid permission problems thus. */
1659 assert(user_and_machine
);
1661 /* Omitting the user name means that we shall use the same user name as we run as locally, which
1662 * means we'll end up on the same host, let's shortcut */
1663 if (STR_IN_SET(user_and_machine
, "@.host", "@"))
1666 /* Otherwise, if we are root, then we can also allow the ".host" syntax, as that's the user this
1667 * would connect to. */
1668 uid_t uid
= geteuid();
1670 if (uid
== 0 && STR_IN_SET(user_and_machine
, ".host", "root@.host", "0@.host"))
1673 /* Otherwise, we have to figure out our user id and name, and compare things with that. */
1674 _cleanup_free_
char *un
= NULL
;
1677 f
= startswith(user_and_machine
, FORMAT_UID(uid
));
1679 un
= getusername_malloc();
1683 f
= startswith(user_and_machine
, un
);
1688 return STR_IN_SET(f
, "@", "@.host");
1691 _public_
int sd_bus_open_system_machine(sd_bus
**ret
, const char *user_and_machine
) {
1692 _cleanup_(bus_freep
) sd_bus
*b
= NULL
;
1695 assert_return(user_and_machine
, -EINVAL
);
1696 assert_return(ret
, -EINVAL
);
1698 if (machine_spec_is_current_identity(user_and_machine
))
1699 return sd_bus_open_system(ret
);
1701 r
= machine_spec_valid(user_and_machine
);
1711 r
= bus_set_address_machine(b
, RUNTIME_SCOPE_SYSTEM
, user_and_machine
);
1715 b
->bus_client
= true;
1716 b
->runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
1718 r
= sd_bus_start(b
);
1726 _public_
int sd_bus_open_user_machine(sd_bus
**ret
, const char *user_and_machine
) {
1727 _cleanup_(bus_freep
) sd_bus
*b
= NULL
;
1730 assert_return(user_and_machine
, -EINVAL
);
1731 assert_return(ret
, -EINVAL
);
1733 /* Shortcut things if we'd end up on this host and as the same user and have one of the necessary
1734 * environment variables set already. */
1735 if (machine_spec_is_current_identity(user_and_machine
) &&
1736 (secure_getenv("DBUS_SESSION_BUS_ADDRESS") || secure_getenv("XDG_RUNTIME_DIR")))
1737 return sd_bus_open_user(ret
);
1739 r
= machine_spec_valid(user_and_machine
);
1749 r
= bus_set_address_machine(b
, RUNTIME_SCOPE_USER
, user_and_machine
);
1753 b
->bus_client
= true;
1756 r
= sd_bus_start(b
);
1764 _public_
void sd_bus_close(sd_bus
*bus
) {
1767 if (bus
->state
== BUS_CLOSED
)
1769 if (bus_origin_changed(bus
))
1772 /* Don't leave ssh hanging around */
1775 bus_set_state(bus
, BUS_CLOSED
);
1777 sd_bus_detach_event(bus
);
1779 /* Drop all queued messages so that they drop references to
1780 * the bus object and the bus may be freed */
1781 bus_reset_queues(bus
);
1786 _public_ sd_bus
* sd_bus_close_unref(sd_bus
*bus
) {
1789 if (bus_origin_changed(bus
))
1794 return sd_bus_unref(bus
);
1797 _public_ sd_bus
* sd_bus_flush_close_unref(sd_bus
*bus
) {
1800 if (bus_origin_changed(bus
))
1803 /* Have to do this before flush() to prevent hang */
1807 return sd_bus_close_unref(bus
);
1810 void bus_enter_closing(sd_bus
*bus
) {
1813 if (!IN_SET(bus
->state
, BUS_WATCH_BIND
, BUS_OPENING
, BUS_AUTHENTICATING
, BUS_HELLO
, BUS_RUNNING
))
1816 bus_set_state(bus
, BUS_CLOSING
);
1819 /* Define manually so we can add the PID check */
1820 _public_ sd_bus
* sd_bus_ref(sd_bus
*bus
) {
1823 if (bus_origin_changed(bus
))
1831 _public_ sd_bus
* sd_bus_unref(sd_bus
*bus
) {
1834 if (bus_origin_changed(bus
))
1837 assert(bus
->n_ref
> 0);
1838 if (--bus
->n_ref
> 0)
1841 return bus_free(bus
);
1844 _public_
int sd_bus_is_open(sd_bus
*bus
) {
1848 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
1849 assert_return(!bus_origin_changed(bus
), -ECHILD
);
1851 return BUS_IS_OPEN(bus
->state
);
1854 _public_
int sd_bus_is_ready(sd_bus
*bus
) {
1858 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
1859 assert_return(!bus_origin_changed(bus
), -ECHILD
);
1861 return bus
->state
== BUS_RUNNING
;
1864 _public_
int sd_bus_can_send(sd_bus
*bus
, char type
) {
1867 assert_return(bus
, -EINVAL
);
1868 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
1869 assert_return(bus
->state
!= BUS_UNSET
, -ENOTCONN
);
1870 assert_return(!bus_origin_changed(bus
), -ECHILD
);
1872 if (bus
->is_monitor
)
1875 if (type
== SD_BUS_TYPE_UNIX_FD
) {
1876 if (!bus
->accept_fd
)
1879 r
= bus_ensure_running(bus
);
1883 return bus
->can_fds
;
1886 return bus_type_is_valid(type
);
1889 _public_
int sd_bus_get_bus_id(sd_bus
*bus
, sd_id128_t
*ret
) {
1892 assert_return(bus
, -EINVAL
);
1893 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
1894 assert_return(ret
, -EINVAL
);
1895 assert_return(!bus_origin_changed(bus
), -ECHILD
);
1897 r
= bus_ensure_running(bus
);
1901 *ret
= bus
->server_id
;
1905 #define COOKIE_CYCLED (UINT32_C(1) << 31)
1907 static uint64_t cookie_inc(uint64_t cookie
) {
1909 /* Stay within the 32-bit range, since classic D-Bus can't deal with more */
1910 if (cookie
>= UINT32_MAX
)
1911 return COOKIE_CYCLED
; /* Don't go back to zero, but use the highest bit for checking
1912 * whether we are looping. */
1917 static int next_cookie(sd_bus
*b
) {
1918 uint64_t new_cookie
;
1922 new_cookie
= cookie_inc(b
->cookie
);
1924 /* Small optimization: don't bother with checking for cookie reuse until we overran cookiespace at
1925 * least once, but then do it thorougly. */
1926 if (FLAGS_SET(new_cookie
, COOKIE_CYCLED
)) {
1929 /* Check if the cookie is currently in use. If so, pick the next one */
1930 for (i
= 0; i
< COOKIE_CYCLED
; i
++) {
1931 if (!ordered_hashmap_contains(b
->reply_callbacks
, &new_cookie
))
1934 new_cookie
= cookie_inc(new_cookie
);
1937 /* Can't fulfill request */
1942 b
->cookie
= new_cookie
;
1946 static int bus_seal_message(sd_bus
*b
, sd_bus_message
*m
, usec_t timeout
) {
1953 /* If we copy the same message to multiple
1954 * destinations, avoid using the same cookie
1956 b
->cookie
= MAX(b
->cookie
, BUS_MESSAGE_COOKIE(m
));
1961 r
= sd_bus_get_method_call_timeout(b
, &timeout
);
1966 if (!m
->sender
&& b
->patch_sender
) {
1967 r
= sd_bus_message_set_sender(m
, b
->patch_sender
);
1976 return sd_bus_message_seal(m
, b
->cookie
, timeout
);
1979 static int bus_remarshal_message(sd_bus
*b
, sd_bus_message
**m
) {
1980 bool remarshal
= false;
1984 /* wrong packet version */
1985 if (b
->message_version
!= 0 && b
->message_version
!= (*m
)->header
->version
)
1988 /* wrong packet endianness */
1989 if (b
->message_endian
!= 0 && b
->message_endian
!= (*m
)->header
->endian
)
1992 return remarshal
? bus_message_remarshal(b
, m
) : 0;
1995 int bus_seal_synthetic_message(sd_bus
*b
, sd_bus_message
*m
) {
1999 /* Fake some timestamps, if they were requested, and not
2000 * already initialized */
2001 if (b
->attach_timestamp
) {
2002 if (m
->realtime
<= 0)
2003 m
->realtime
= now(CLOCK_REALTIME
);
2005 if (m
->monotonic
<= 0)
2006 m
->monotonic
= now(CLOCK_MONOTONIC
);
2009 /* The bus specification says the serial number cannot be 0,
2010 * hence let's fill something in for synthetic messages. Since
2011 * synthetic messages might have a fake sender and we don't
2012 * want to interfere with the real sender's serial numbers we
2013 * pick a fixed, artificial one. */
2014 return sd_bus_message_seal(m
, UINT32_MAX
, 0);
2017 static int bus_write_message(sd_bus
*bus
, sd_bus_message
*m
, size_t *idx
) {
2023 r
= bus_socket_write_message(bus
, m
, idx
);
2027 if (*idx
>= BUS_MESSAGE_SIZE(m
))
2028 log_debug("Sent message type=%s sender=%s destination=%s path=%s interface=%s member=%s"
2029 " cookie=%" PRIu64
" reply_cookie=%" PRIu64
2030 " signature=%s error-name=%s error-message=%s",
2031 bus_message_type_to_string(m
->header
->type
),
2032 strna(sd_bus_message_get_sender(m
)),
2033 strna(sd_bus_message_get_destination(m
)),
2034 strna(sd_bus_message_get_path(m
)),
2035 strna(sd_bus_message_get_interface(m
)),
2036 strna(sd_bus_message_get_member(m
)),
2037 BUS_MESSAGE_COOKIE(m
),
2039 strna(m
->root_container
.signature
),
2040 strna(m
->error
.name
),
2041 strna(m
->error
.message
));
2046 static int dispatch_wqueue(sd_bus
*bus
) {
2050 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
2052 while (bus
->wqueue_size
> 0) {
2054 r
= bus_write_message(bus
, bus
->wqueue
[0], &bus
->windex
);
2058 /* Didn't do anything this time */
2060 if (bus
->windex
>= BUS_MESSAGE_SIZE(bus
->wqueue
[0])) {
2061 /* Fully written. Let's drop the entry from
2064 * This isn't particularly optimized, but
2065 * well, this is supposed to be our worst-case
2066 * buffer only, and the socket buffer is
2067 * supposed to be our primary buffer, and if
2068 * it got full, then all bets are off
2072 bus_message_unref_queued(bus
->wqueue
[0], bus
);
2073 memmove(bus
->wqueue
, bus
->wqueue
+ 1, sizeof(sd_bus_message
*) * bus
->wqueue_size
);
2083 static int bus_read_message(sd_bus
*bus
) {
2086 return bus_socket_read_message(bus
);
2089 int bus_rqueue_make_room(sd_bus
*bus
) {
2092 if (bus
->rqueue_size
>= BUS_RQUEUE_MAX
)
2095 if (!GREEDY_REALLOC(bus
->rqueue
, bus
->rqueue_size
+ 1))
2101 static void rqueue_drop_one(sd_bus
*bus
, size_t i
) {
2103 assert(i
< bus
->rqueue_size
);
2105 bus_message_unref_queued(bus
->rqueue
[i
], bus
);
2106 memmove(bus
->rqueue
+ i
, bus
->rqueue
+ i
+ 1, sizeof(sd_bus_message
*) * (bus
->rqueue_size
- i
- 1));
2110 static int dispatch_rqueue(sd_bus
*bus
, sd_bus_message
**m
) {
2115 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
2118 if (bus
->rqueue_size
> 0) {
2119 /* Dispatch a queued message */
2120 *m
= sd_bus_message_ref(bus
->rqueue
[0]);
2121 rqueue_drop_one(bus
, 0);
2125 /* Try to read a new message */
2126 r
= bus_read_message(bus
);
2138 _public_
int sd_bus_send(sd_bus
*bus
, sd_bus_message
*_m
, uint64_t *ret_cookie
) {
2139 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= sd_bus_message_ref(_m
);
2142 assert_return(m
, -EINVAL
);
2145 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
2147 assert_return(bus
= m
->bus
, -ENOTCONN
);
2148 assert_return(!bus_origin_changed(bus
), -ECHILD
);
2150 if (!BUS_IS_OPEN(bus
->state
))
2154 r
= sd_bus_can_send(bus
, SD_BUS_TYPE_UNIX_FD
);
2161 /* If the cookie number isn't kept, then we know that no reply
2163 if (!ret_cookie
&& !m
->sealed
)
2164 m
->header
->flags
|= BUS_MESSAGE_NO_REPLY_EXPECTED
;
2166 r
= bus_seal_message(bus
, m
, 0);
2170 /* Remarshall if we have to. This will possibly unref the
2171 * message and place a replacement in m */
2172 r
= bus_remarshal_message(bus
, &m
);
2176 /* If this is a reply and no reply was requested, then let's
2177 * suppress this, if we can */
2181 if (IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
) && bus
->wqueue_size
<= 0) {
2184 r
= bus_write_message(bus
, m
, &idx
);
2185 if (ERRNO_IS_NEG_DISCONNECT(r
)) {
2186 bus_enter_closing(bus
);
2191 if (idx
< BUS_MESSAGE_SIZE(m
)) {
2192 /* Wasn't fully written. So let's remember how
2193 * much was written. Note that the first entry
2194 * of the wqueue array is always allocated so
2195 * that we always can remember how much was
2197 bus
->wqueue
[0] = bus_message_ref_queued(m
, bus
);
2198 bus
->wqueue_size
= 1;
2203 /* Just append it to the queue. */
2205 if (bus
->wqueue_size
>= BUS_WQUEUE_MAX
)
2208 if (!GREEDY_REALLOC(bus
->wqueue
, bus
->wqueue_size
+ 1))
2211 bus
->wqueue
[bus
->wqueue_size
++] = bus_message_ref_queued(m
, bus
);
2216 *ret_cookie
= BUS_MESSAGE_COOKIE(m
);
2221 _public_
int sd_bus_send_to(sd_bus
*bus
, sd_bus_message
*m
, const char *destination
, uint64_t *ret_cookie
) {
2224 assert_return(m
, -EINVAL
);
2227 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
2229 assert_return(bus
= m
->bus
, -ENOTCONN
);
2230 assert_return(!bus_origin_changed(bus
), -ECHILD
);
2232 if (!BUS_IS_OPEN(bus
->state
))
2235 if (!streq_ptr(m
->destination
, destination
)) {
2240 r
= sd_bus_message_set_destination(m
, destination
);
2245 return sd_bus_send(bus
, m
, ret_cookie
);
2248 static usec_t
calc_elapse(sd_bus
*bus
, uint64_t usec
) {
2251 assert_cc(sizeof(usec_t
) == sizeof(uint64_t));
2253 if (usec
== USEC_INFINITY
)
2256 /* We start all timeouts the instant we enter BUS_HELLO/BUS_RUNNING state, so that the don't run in parallel
2257 * with any connection setup states. Hence, if a method callback is started earlier than that we just store the
2258 * relative timestamp, and afterwards the absolute one. */
2260 if (IN_SET(bus
->state
, BUS_WATCH_BIND
, BUS_OPENING
, BUS_AUTHENTICATING
))
2263 return usec_add(now(CLOCK_MONOTONIC
), usec
);
2266 static int timeout_compare(const void *a
, const void *b
) {
2267 const BusReplyCallback
*x
= a
, *y
= b
;
2269 if (x
->timeout_usec
!= 0 && y
->timeout_usec
== 0)
2272 if (x
->timeout_usec
== 0 && y
->timeout_usec
!= 0)
2275 return CMP(x
->timeout_usec
, y
->timeout_usec
);
2278 _public_
int sd_bus_call_async(
2280 sd_bus_slot
**ret_slot
,
2282 sd_bus_message_handler_t callback
,
2286 _unused_
_cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m_unref
= sd_bus_message_ref(m
);
2287 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*s
= NULL
;
2290 assert_return(m
, -EINVAL
);
2291 assert_return(m
->header
->type
== SD_BUS_MESSAGE_METHOD_CALL
, -EINVAL
);
2292 assert_return(!m
->sealed
|| (!!callback
== !(m
->header
->flags
& BUS_MESSAGE_NO_REPLY_EXPECTED
)), -EINVAL
);
2295 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
2297 assert_return(bus
= m
->bus
, -ENOTCONN
);
2298 assert_return(!bus_origin_changed(bus
), -ECHILD
);
2300 if (!BUS_IS_OPEN(bus
->state
))
2303 /* If no callback is specified and there's no interest in a slot, then there's no reason to ask for a reply */
2304 if (!callback
&& !ret_slot
&& !m
->sealed
)
2305 m
->header
->flags
|= BUS_MESSAGE_NO_REPLY_EXPECTED
;
2307 r
= prioq_ensure_allocated(&bus
->reply_callbacks_prioq
, timeout_compare
);
2311 r
= bus_seal_message(bus
, m
, usec
);
2315 r
= bus_remarshal_message(bus
, &m
);
2319 if (ret_slot
|| callback
) {
2320 s
= bus_slot_allocate(bus
, !ret_slot
, BUS_REPLY_CALLBACK
, sizeof(BusReplyCallback
), userdata
);
2324 s
->reply_callback
.callback
= callback
;
2326 s
->reply_callback
.cookie
= BUS_MESSAGE_COOKIE(m
);
2327 r
= ordered_hashmap_ensure_put(&bus
->reply_callbacks
, &uint64_hash_ops_value_free
, &s
->reply_callback
.cookie
, &s
->reply_callback
);
2329 s
->reply_callback
.cookie
= 0;
2333 s
->reply_callback
.timeout_usec
= calc_elapse(bus
, m
->timeout
);
2334 if (s
->reply_callback
.timeout_usec
!= 0) {
2335 r
= prioq_put(bus
->reply_callbacks_prioq
, &s
->reply_callback
, &s
->reply_callback
.prioq_idx
);
2337 s
->reply_callback
.timeout_usec
= 0;
2343 r
= sd_bus_send(bus
, m
, s
? &s
->reply_callback
.cookie
: NULL
);
2354 int bus_ensure_running(sd_bus
*bus
) {
2359 if (bus
->state
== BUS_RUNNING
)
2363 if (IN_SET(bus
->state
, BUS_UNSET
, BUS_CLOSED
, BUS_CLOSING
))
2366 r
= sd_bus_process(bus
, NULL
);
2369 if (bus
->state
== BUS_RUNNING
)
2374 r
= sd_bus_wait(bus
, UINT64_MAX
);
2380 _public_
int sd_bus_call(
2384 sd_bus_error
*reterr_error
,
2385 sd_bus_message
**ret_reply
) {
2387 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= sd_bus_message_ref(_m
);
2393 bus_assert_return(m
, -EINVAL
, reterr_error
);
2394 bus_assert_return(m
->header
->type
== SD_BUS_MESSAGE_METHOD_CALL
, -EINVAL
, reterr_error
);
2395 bus_assert_return(!(m
->header
->flags
& BUS_MESSAGE_NO_REPLY_EXPECTED
), -EINVAL
, reterr_error
);
2396 bus_assert_return(!bus_error_is_dirty(reterr_error
), -EINVAL
, reterr_error
);
2399 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
2401 assert_return(bus
= m
->bus
, -ENOTCONN
);
2402 bus_assert_return(!bus_origin_changed(bus
), -ECHILD
, reterr_error
);
2404 if (!BUS_IS_OPEN(bus
->state
)) {
2409 r
= bus_ensure_running(bus
);
2413 i
= bus
->rqueue_size
;
2415 r
= bus_seal_message(bus
, m
, usec
);
2419 r
= bus_remarshal_message(bus
, &m
);
2423 r
= sd_bus_send(bus
, m
, &cookie
);
2427 timeout
= calc_elapse(bus
, m
->timeout
);
2432 while (i
< bus
->rqueue_size
) {
2433 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*incoming
= NULL
;
2435 incoming
= sd_bus_message_ref(bus
->rqueue
[i
]);
2437 if (incoming
->reply_cookie
== cookie
) {
2438 /* Found a match! */
2440 rqueue_drop_one(bus
, i
);
2441 log_debug_bus_message(incoming
);
2443 if (incoming
->header
->type
== SD_BUS_MESSAGE_METHOD_RETURN
) {
2445 if (incoming
->n_fds
<= 0 || bus
->accept_fd
) {
2447 *ret_reply
= TAKE_PTR(incoming
);
2452 return sd_bus_error_set(reterr_error
, SD_BUS_ERROR_INCONSISTENT_MESSAGE
,
2453 "Reply message contained file descriptors which I couldn't accept. Sorry.");
2455 } else if (incoming
->header
->type
== SD_BUS_MESSAGE_METHOD_ERROR
)
2456 return sd_bus_error_copy(reterr_error
, &incoming
->error
);
2462 } else if (BUS_MESSAGE_COOKIE(incoming
) == cookie
&&
2465 streq(bus
->unique_name
, incoming
->sender
)) {
2467 rqueue_drop_one(bus
, i
);
2469 /* Our own message? Somebody is trying to send its own client a message,
2470 * let's not dead-lock, let's fail immediately. */
2476 /* Try to read more, right-away */
2480 r
= bus_read_message(bus
);
2482 if (ERRNO_IS_DISCONNECT(r
)) {
2483 bus_enter_closing(bus
);
2495 n
= now(CLOCK_MONOTONIC
);
2505 r
= bus_poll(bus
, true, left
);
2506 if (ERRNO_IS_NEG_TRANSIENT(r
))
2515 r
= dispatch_wqueue(bus
);
2517 if (ERRNO_IS_DISCONNECT(r
)) {
2518 bus_enter_closing(bus
);
2527 return sd_bus_error_set_errno(reterr_error
, r
);
2530 _public_
int sd_bus_get_fd(sd_bus
*bus
) {
2531 assert_return(bus
, -EINVAL
);
2532 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
2533 assert_return(bus
->input_fd
== bus
->output_fd
, -EPERM
);
2534 assert_return(!bus_origin_changed(bus
), -ECHILD
);
2536 if (bus
->state
== BUS_CLOSED
)
2539 if (bus
->inotify_fd
>= 0)
2540 return bus
->inotify_fd
;
2542 if (bus
->input_fd
>= 0)
2543 return bus
->input_fd
;
2548 _public_
int sd_bus_get_events(sd_bus
*bus
) {
2551 assert_return(bus
, -EINVAL
);
2552 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
2553 assert_return(!bus_origin_changed(bus
), -ECHILD
);
2555 switch (bus
->state
) {
2561 case BUS_WATCH_BIND
:
2569 case BUS_AUTHENTICATING
:
2570 if (bus_socket_auth_needs_write(bus
))
2578 if (bus
->rqueue_size
<= 0)
2580 if (bus
->wqueue_size
> 0)
2588 assert_not_reached();
2594 _public_
int sd_bus_get_timeout(sd_bus
*bus
, uint64_t *ret
) {
2595 BusReplyCallback
*c
;
2597 assert_return(bus
, -EINVAL
);
2598 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
2599 assert_return(ret
, -EINVAL
);
2600 assert_return(!bus_origin_changed(bus
), -ECHILD
);
2602 if (!BUS_IS_OPEN(bus
->state
) && bus
->state
!= BUS_CLOSING
)
2605 if (bus
->track_queue
) {
2610 switch (bus
->state
) {
2612 case BUS_AUTHENTICATING
:
2613 *ret
= bus
->auth_timeout
;
2618 if (bus
->rqueue_size
> 0) {
2623 c
= prioq_peek(bus
->reply_callbacks_prioq
);
2629 if (c
->timeout_usec
== 0) {
2634 *ret
= c
->timeout_usec
;
2641 case BUS_WATCH_BIND
:
2647 assert_not_reached();
2651 static int process_timeout(sd_bus
*bus
) {
2652 _cleanup_(sd_bus_error_free
) sd_bus_error error_buffer
= SD_BUS_ERROR_NULL
;
2653 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
* m
= NULL
;
2654 BusReplyCallback
*c
;
2661 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
2663 c
= prioq_peek(bus
->reply_callbacks_prioq
);
2667 n
= now(CLOCK_MONOTONIC
);
2668 if (c
->timeout_usec
> n
)
2671 r
= bus_message_new_synthetic_error(
2674 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY
, "Method call timed out"),
2679 m
->read_counter
= ++bus
->read_counter
;
2681 r
= bus_seal_synthetic_message(bus
, m
);
2685 assert_se(prioq_pop(bus
->reply_callbacks_prioq
) == c
);
2686 c
->timeout_usec
= 0;
2688 ordered_hashmap_remove(bus
->reply_callbacks
, &c
->cookie
);
2691 slot
= container_of(c
, sd_bus_slot
, reply_callback
);
2693 bus
->iteration_counter
++;
2695 is_hello
= bus
->state
== BUS_HELLO
&& c
->callback
== hello_callback
;
2697 bus
->current_message
= m
;
2698 bus
->current_slot
= sd_bus_slot_ref(slot
);
2699 bus
->current_handler
= c
->callback
;
2700 bus
->current_userdata
= slot
->userdata
;
2701 r
= c
->callback(m
, slot
->userdata
, &error_buffer
);
2702 bus
->current_userdata
= NULL
;
2703 bus
->current_handler
= NULL
;
2704 bus
->current_slot
= NULL
;
2705 bus
->current_message
= NULL
;
2708 bus_slot_disconnect(slot
, true);
2710 sd_bus_slot_unref(slot
);
2712 /* When this is the hello message and it timed out, then make sure to propagate the error up, don't just log
2713 * and ignore the callback handler's return value. */
2717 return bus_maybe_reply_error(m
, r
, &error_buffer
);
2720 static int process_hello(sd_bus
*bus
, sd_bus_message
*m
) {
2724 if (bus
->state
!= BUS_HELLO
)
2727 /* Let's make sure the first message on the bus is the HELLO
2728 * reply. But note that we don't actually parse the message
2729 * here (we leave that to the usual handling), we just verify
2730 * we don't let any earlier msg through. */
2732 if (!IN_SET(m
->header
->type
, SD_BUS_MESSAGE_METHOD_RETURN
, SD_BUS_MESSAGE_METHOD_ERROR
))
2735 if (m
->reply_cookie
!= 1)
2741 static int process_reply(sd_bus
*bus
, sd_bus_message
*m
) {
2742 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*synthetic_reply
= NULL
;
2743 _cleanup_(sd_bus_error_free
) sd_bus_error error_buffer
= SD_BUS_ERROR_NULL
;
2744 BusReplyCallback
*c
;
2752 if (!IN_SET(m
->header
->type
, SD_BUS_MESSAGE_METHOD_RETURN
, SD_BUS_MESSAGE_METHOD_ERROR
))
2755 if (m
->destination
&& bus
->unique_name
&& !streq_ptr(m
->destination
, bus
->unique_name
))
2758 c
= ordered_hashmap_remove(bus
->reply_callbacks
, &m
->reply_cookie
);
2764 slot
= container_of(c
, sd_bus_slot
, reply_callback
);
2766 if (m
->n_fds
> 0 && !bus
->accept_fd
) {
2768 /* If the reply contained a file descriptor which we
2769 * didn't want we pass an error instead. */
2771 r
= bus_message_new_synthetic_error(
2774 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INCONSISTENT_MESSAGE
, "Reply message contained file descriptor"),
2779 /* Copy over original timestamp */
2780 synthetic_reply
->realtime
= m
->realtime
;
2781 synthetic_reply
->monotonic
= m
->monotonic
;
2782 synthetic_reply
->seqnum
= m
->seqnum
;
2783 synthetic_reply
->read_counter
= m
->read_counter
;
2785 r
= bus_seal_synthetic_message(bus
, synthetic_reply
);
2789 m
= synthetic_reply
;
2791 r
= sd_bus_message_rewind(m
, true);
2796 if (c
->timeout_usec
!= 0) {
2797 prioq_remove(bus
->reply_callbacks_prioq
, c
, &c
->prioq_idx
);
2798 c
->timeout_usec
= 0;
2801 is_hello
= bus
->state
== BUS_HELLO
&& c
->callback
== hello_callback
;
2803 bus
->current_slot
= sd_bus_slot_ref(slot
);
2804 bus
->current_handler
= c
->callback
;
2805 bus
->current_userdata
= slot
->userdata
;
2806 r
= c
->callback(m
, slot
->userdata
, &error_buffer
);
2807 bus
->current_userdata
= NULL
;
2808 bus
->current_handler
= NULL
;
2809 bus
->current_slot
= NULL
;
2812 bus_slot_disconnect(slot
, true);
2814 sd_bus_slot_unref(slot
);
2816 /* When this is the hello message and it failed, then make sure to propagate the error up, don't just log and
2817 * ignore the callback handler's return value. */
2821 return bus_maybe_reply_error(m
, r
, &error_buffer
);
2824 static int process_filter(sd_bus
*bus
, sd_bus_message
*m
) {
2825 _cleanup_(sd_bus_error_free
) sd_bus_error error_buffer
= SD_BUS_ERROR_NULL
;
2832 bus
->filter_callbacks_modified
= false;
2834 LIST_FOREACH(callbacks
, l
, bus
->filter_callbacks
) {
2837 if (bus
->filter_callbacks_modified
)
2840 /* Don't run this more than once per iteration */
2841 if (l
->last_iteration
== bus
->iteration_counter
)
2844 l
->last_iteration
= bus
->iteration_counter
;
2846 r
= sd_bus_message_rewind(m
, true);
2850 slot
= container_of(l
, sd_bus_slot
, filter_callback
);
2852 bus
->current_slot
= sd_bus_slot_ref(slot
);
2853 bus
->current_handler
= l
->callback
;
2854 bus
->current_userdata
= slot
->userdata
;
2855 r
= l
->callback(m
, slot
->userdata
, &error_buffer
);
2856 bus
->current_userdata
= NULL
;
2857 bus
->current_handler
= NULL
;
2858 bus
->current_slot
= sd_bus_slot_unref(slot
);
2860 r
= bus_maybe_reply_error(m
, r
, &error_buffer
);
2866 } while (bus
->filter_callbacks_modified
);
2871 static int process_match(sd_bus
*bus
, sd_bus_message
*m
) {
2878 bus
->match_callbacks_modified
= false;
2880 r
= bus_match_run(bus
, &bus
->match_callbacks
, m
);
2884 } while (bus
->match_callbacks_modified
);
2889 static int process_builtin(sd_bus
*bus
, sd_bus_message
*m
) {
2890 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
2896 if (bus
->is_monitor
)
2899 if (bus
->manual_peer_interface
)
2902 if (m
->header
->type
!= SD_BUS_MESSAGE_METHOD_CALL
)
2905 if (!streq_ptr(m
->interface
, "org.freedesktop.DBus.Peer"))
2908 if (m
->header
->flags
& BUS_MESSAGE_NO_REPLY_EXPECTED
)
2911 if (streq_ptr(m
->member
, "Ping"))
2912 r
= sd_bus_message_new_method_return(m
, &reply
);
2913 else if (streq_ptr(m
->member
, "GetMachineId")) {
2916 r
= sd_id128_get_machine(&id
);
2920 r
= sd_bus_message_new_method_return(m
, &reply
);
2924 r
= sd_bus_message_append(reply
, "s", SD_ID128_TO_STRING(id
));
2926 r
= sd_bus_message_new_method_errorf(
2928 SD_BUS_ERROR_UNKNOWN_METHOD
,
2929 "Unknown method '%s' on interface '%s'.", m
->member
, m
->interface
);
2933 r
= sd_bus_send(bus
, reply
, NULL
);
2940 static int process_fd_check(sd_bus
*bus
, sd_bus_message
*m
) {
2944 /* If we got a message with a file descriptor which we didn't
2945 * want to accept, then let's drop it. How can this even
2946 * happen? For example, when the kernel queues a message into
2947 * an activatable names's queue which allows fds, and then is
2948 * delivered to us later even though we ourselves did not
2951 if (bus
->is_monitor
)
2960 if (m
->header
->type
!= SD_BUS_MESSAGE_METHOD_CALL
)
2961 return 1; /* just eat it up */
2963 return sd_bus_reply_method_errorf(m
, SD_BUS_ERROR_INCONSISTENT_MESSAGE
,
2964 "Message contains file descriptors, which I cannot accept. Sorry.");
2967 static int process_message(sd_bus
*bus
, sd_bus_message
*m
) {
2968 _unused_
_cleanup_(log_context_unrefp
) LogContext
*c
= NULL
;
2974 bus
->current_message
= m
;
2975 bus
->iteration_counter
++;
2977 if (log_context_enabled())
2978 c
= log_context_new_strv_consume(bus_message_make_log_fields(m
));
2980 log_debug_bus_message(m
);
2982 r
= process_hello(bus
, m
);
2986 r
= process_reply(bus
, m
);
2990 r
= process_fd_check(bus
, m
);
2994 r
= process_filter(bus
, m
);
2998 r
= process_match(bus
, m
);
3002 r
= process_builtin(bus
, m
);
3006 r
= bus_process_object(bus
, m
);
3009 bus
->current_message
= NULL
;
3013 static int dispatch_track(sd_bus
*bus
) {
3016 if (!bus
->track_queue
)
3019 bus_track_dispatch(bus
->track_queue
);
3023 static int process_running(sd_bus
*bus
, sd_bus_message
**ret
) {
3024 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
3028 assert(IN_SET(bus
->state
, BUS_RUNNING
, BUS_HELLO
));
3030 r
= process_timeout(bus
);
3034 r
= dispatch_wqueue(bus
);
3038 r
= dispatch_track(bus
);
3042 r
= dispatch_rqueue(bus
, &m
);
3048 r
= process_message(bus
, m
);
3053 r
= sd_bus_message_rewind(m
, true);
3061 if (m
->header
->type
== SD_BUS_MESSAGE_METHOD_CALL
) {
3063 log_debug("Unprocessed message call sender=%s object=%s interface=%s member=%s",
3064 strna(sd_bus_message_get_sender(m
)),
3065 strna(sd_bus_message_get_path(m
)),
3066 strna(sd_bus_message_get_interface(m
)),
3067 strna(sd_bus_message_get_member(m
)));
3069 r
= sd_bus_reply_method_errorf(
3071 SD_BUS_ERROR_UNKNOWN_OBJECT
,
3072 "Unknown object '%s'.", m
->path
);
3086 static int bus_exit_now(sd_bus
*bus
, sd_event
*event
) {
3089 /* Exit due to close, if this is requested. If this is bus object is attached to an event source, invokes
3090 * sd_event_exit(), otherwise invokes libc exit(). */
3092 if (bus
->exited
) /* did we already exit? */
3094 if (!bus
->exit_triggered
) /* was the exit condition triggered? */
3096 if (!bus
->exit_on_disconnect
) /* Shall we actually exit on disconnection? */
3099 bus
->exited
= true; /* never exit more than once */
3101 log_debug("Bus connection disconnected, exiting.");
3107 return sd_event_exit(event
, EXIT_FAILURE
);
3110 assert_not_reached();
3113 static int process_closing_reply_callback(sd_bus
*bus
, BusReplyCallback
*c
) {
3114 _cleanup_(sd_bus_error_free
) sd_bus_error error_buffer
= SD_BUS_ERROR_NULL
;
3115 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
3122 r
= bus_message_new_synthetic_error(
3125 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY
, "Connection terminated"),
3130 m
->read_counter
= ++bus
->read_counter
;
3132 r
= bus_seal_synthetic_message(bus
, m
);
3136 if (c
->timeout_usec
!= 0) {
3137 prioq_remove(bus
->reply_callbacks_prioq
, c
, &c
->prioq_idx
);
3138 c
->timeout_usec
= 0;
3141 ordered_hashmap_remove(bus
->reply_callbacks
, &c
->cookie
);
3144 slot
= container_of(c
, sd_bus_slot
, reply_callback
);
3146 bus
->iteration_counter
++;
3148 bus
->current_message
= m
;
3149 bus
->current_slot
= sd_bus_slot_ref(slot
);
3150 bus
->current_handler
= c
->callback
;
3151 bus
->current_userdata
= slot
->userdata
;
3152 r
= c
->callback(m
, slot
->userdata
, &error_buffer
);
3153 bus
->current_userdata
= NULL
;
3154 bus
->current_handler
= NULL
;
3155 bus
->current_slot
= NULL
;
3156 bus
->current_message
= NULL
;
3159 bus_slot_disconnect(slot
, true);
3161 sd_bus_slot_unref(slot
);
3163 return bus_maybe_reply_error(m
, r
, &error_buffer
);
3166 static int process_closing(sd_bus
*bus
, sd_bus_message
**ret
) {
3167 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
3168 _cleanup_(sd_event_unrefp
) sd_event
*event
= NULL
;
3169 BusReplyCallback
*c
;
3173 assert(bus
->state
== BUS_CLOSING
);
3175 /* First, fail all outstanding method calls */
3176 c
= ordered_hashmap_first(bus
->reply_callbacks
);
3178 return process_closing_reply_callback(bus
, c
);
3180 /* Then, fake-drop all remaining bus tracking references */
3182 bus_track_close(bus
->tracks
);
3186 /* Then, synthesize a Disconnected message */
3187 r
= sd_bus_message_new_signal(
3190 "/org/freedesktop/DBus/Local",
3191 "org.freedesktop.DBus.Local",
3196 bus_message_set_sender_local(bus
, m
);
3197 m
->read_counter
= ++bus
->read_counter
;
3199 r
= bus_seal_synthetic_message(bus
, m
);
3203 /* sd_bus_close() will deref the event and set bus->event to NULL. But in bus_exit_now() we use
3204 * bus->event to decide whether to return from the event loop or exit(), but given it's always NULL
3205 * at that point, it always exit(). Ref it here and pass it through further down to avoid that. */
3206 event
= sd_event_ref(bus
->event
);
3209 bus
->current_message
= m
;
3210 bus
->iteration_counter
++;
3212 r
= process_filter(bus
, m
);
3216 r
= process_match(bus
, m
);
3220 /* Nothing else to do, exit now, if the condition holds */
3221 bus
->exit_triggered
= true;
3222 (void) bus_exit_now(bus
, event
);
3230 bus
->current_message
= NULL
;
3235 static int bus_process_internal(sd_bus
*bus
, sd_bus_message
**ret
) {
3238 /* Returns 0 when we didn't do anything. This should cause the
3239 * caller to invoke sd_bus_wait() before returning the next
3240 * time. Returns > 0 when we did something, which possibly
3241 * means *ret is filled in with an unprocessed message. */
3243 assert_return(bus
, -EINVAL
);
3244 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
3245 assert_return(!bus_origin_changed(bus
), -ECHILD
);
3247 /* We don't allow recursively invoking sd_bus_process(). */
3248 assert_return(!bus
->current_message
, -EBUSY
);
3249 assert(!bus
->current_slot
); /* This should be NULL whenever bus->current_message is */
3251 BUS_DONT_DESTROY(bus
);
3253 switch (bus
->state
) {
3261 case BUS_WATCH_BIND
:
3262 r
= bus_socket_process_watch_bind(bus
);
3266 r
= bus_socket_process_opening(bus
);
3269 case BUS_AUTHENTICATING
:
3270 r
= bus_socket_process_authenticating(bus
);
3275 r
= process_running(bus
, ret
);
3279 /* This branch initializes *ret, hence we don't use the generic error checking below */
3283 return process_closing(bus
, ret
);
3286 assert_not_reached();
3289 if (ERRNO_IS_NEG_DISCONNECT(r
)) {
3290 bus_enter_closing(bus
);
3301 _public_
int sd_bus_process(sd_bus
*bus
, sd_bus_message
**ret
) {
3302 return bus_process_internal(bus
, ret
);
3305 _public_
int sd_bus_process_priority(sd_bus
*bus
, int64_t priority
, sd_bus_message
**ret
) {
3306 return bus_process_internal(bus
, ret
);
3309 static int bus_poll(sd_bus
*bus
, bool need_more
, uint64_t timeout_usec
) {
3310 struct pollfd p
[2] = {};
3311 usec_t m
= USEC_INFINITY
;
3316 if (bus
->state
== BUS_CLOSING
)
3319 if (!BUS_IS_OPEN(bus
->state
))
3322 if (bus
->state
== BUS_WATCH_BIND
) {
3323 assert(bus
->inotify_fd
>= 0);
3325 p
[0].events
= POLLIN
;
3326 p
[0].fd
= bus
->inotify_fd
;
3331 e
= sd_bus_get_events(bus
);
3336 /* The caller really needs some more data, they don't
3337 * care about what's already read, or any timeouts
3338 * except its own. */
3342 /* The caller wants to process if there's something to
3343 * process, but doesn't care otherwise */
3345 r
= sd_bus_get_timeout(bus
, &until
);
3349 m
= usec_sub_unsigned(until
, now(CLOCK_MONOTONIC
));
3352 p
[0].fd
= bus
->input_fd
;
3353 if (bus
->output_fd
== bus
->input_fd
) {
3357 p
[0].events
= e
& POLLIN
;
3358 p
[1].fd
= bus
->output_fd
;
3359 p
[1].events
= e
& POLLOUT
;
3364 if (timeout_usec
!= UINT64_MAX
&& (m
== USEC_INFINITY
|| timeout_usec
< m
))
3367 r
= ppoll_usec(p
, n
, m
);
3374 _public_
int sd_bus_wait(sd_bus
*bus
, uint64_t timeout_usec
) {
3377 assert_return(bus
, -EINVAL
);
3378 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
3379 assert_return(!bus_origin_changed(bus
), -ECHILD
);
3381 if (bus
->state
== BUS_CLOSING
)
3384 if (!BUS_IS_OPEN(bus
->state
))
3387 if (bus
->rqueue_size
> 0)
3390 r
= bus_poll(bus
, false, timeout_usec
);
3391 if (ERRNO_IS_NEG_TRANSIENT(r
))
3392 return 1; /* treat EINTR as success, but let's exit, so that the caller will call back into us soon. */
3397 _public_
int sd_bus_flush(sd_bus
*bus
) {
3400 assert_return(bus
, -EINVAL
);
3401 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
3402 assert_return(!bus_origin_changed(bus
), -ECHILD
);
3404 if (bus
->state
== BUS_CLOSING
)
3407 if (!BUS_IS_OPEN(bus
->state
))
3410 /* We never were connected? Don't hang in inotify for good, as there's no timeout set for it */
3411 if (bus
->state
== BUS_WATCH_BIND
)
3414 r
= bus_ensure_running(bus
);
3418 if (bus
->wqueue_size
<= 0)
3422 r
= dispatch_wqueue(bus
);
3423 if (ERRNO_IS_NEG_DISCONNECT(r
)) {
3424 bus_enter_closing(bus
);
3429 if (bus
->wqueue_size
<= 0)
3432 r
= bus_poll(bus
, false, UINT64_MAX
);
3433 if (ERRNO_IS_NEG_TRANSIENT(r
))
3440 _public_
int sd_bus_add_filter(
3442 sd_bus_slot
**ret_slot
,
3443 sd_bus_message_handler_t callback
,
3448 assert_return(bus
, -EINVAL
);
3449 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
3450 assert_return(callback
, -EINVAL
);
3451 assert_return(!bus_origin_changed(bus
), -ECHILD
);
3453 s
= bus_slot_allocate(bus
, !ret_slot
, BUS_FILTER_CALLBACK
, sizeof(BusFilterCallback
), userdata
);
3457 s
->filter_callback
.callback
= callback
;
3459 bus
->filter_callbacks_modified
= true;
3460 LIST_PREPEND(callbacks
, bus
->filter_callbacks
, &s
->filter_callback
);
3468 static int add_match_callback(
3471 sd_bus_error
*ret_error
) {
3473 sd_bus_slot
*match_slot
= ASSERT_PTR(userdata
);
3474 bool failed
= false;
3479 sd_bus_slot_ref(match_slot
);
3481 if (sd_bus_message_is_method_error(m
, NULL
)) {
3482 log_debug_errno(sd_bus_message_get_errno(m
),
3483 "Unable to add match %s, failing connection: %s",
3484 match_slot
->match_callback
.match_string
,
3485 sd_bus_message_get_error(m
)->message
);
3489 log_debug("Match %s successfully installed.", match_slot
->match_callback
.match_string
);
3491 if (match_slot
->match_callback
.install_callback
) {
3494 bus
= sd_bus_message_get_bus(m
);
3496 /* This function has been called as slot handler, and we want to call another slot handler. Let's
3497 * update the slot callback metadata temporarily with our own data, and then revert back to the old
3500 assert(bus
->current_slot
== match_slot
->match_callback
.install_slot
);
3501 assert(bus
->current_handler
== add_match_callback
);
3502 assert(bus
->current_userdata
== userdata
);
3504 bus
->current_slot
= match_slot
;
3505 bus
->current_handler
= match_slot
->match_callback
.install_callback
;
3506 bus
->current_userdata
= match_slot
->userdata
;
3508 r
= match_slot
->match_callback
.install_callback(m
, match_slot
->userdata
, ret_error
);
3510 bus
->current_slot
= match_slot
->match_callback
.install_slot
;
3511 bus
->current_handler
= add_match_callback
;
3512 bus
->current_userdata
= userdata
;
3514 if (failed
) /* Generic failure handling: destroy the connection */
3515 bus_enter_closing(sd_bus_message_get_bus(m
));
3520 /* We don't need the install method reply slot anymore, let's free it */
3521 match_slot
->match_callback
.install_slot
= sd_bus_slot_unref(match_slot
->match_callback
.install_slot
);
3523 if (failed
&& match_slot
->floating
)
3524 bus_slot_disconnect(match_slot
, true);
3526 sd_bus_slot_unref(match_slot
);
3531 int bus_add_match_full(
3533 sd_bus_slot
**ret_slot
,
3536 sd_bus_message_handler_t callback
,
3537 sd_bus_message_handler_t install_callback
,
3539 uint64_t timeout_usec
) {
3541 BusMatchComponent
*components
= NULL
;
3542 size_t n_components
= 0;
3543 _cleanup_(sd_bus_slot_unrefp
) sd_bus_slot
*s
= NULL
;
3546 assert_return(bus
, -EINVAL
);
3547 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
3548 assert_return(match
, -EINVAL
);
3549 assert_return(!bus_origin_changed(bus
), -ECHILD
);
3551 CLEANUP_ARRAY(components
, n_components
, bus_match_parse_free
);
3553 r
= bus_match_parse(match
, &components
, &n_components
);
3557 s
= bus_slot_allocate(bus
, !ret_slot
, BUS_MATCH_CALLBACK
, sizeof(BusMatchCallback
), userdata
);
3561 s
->match_callback
.callback
= callback
;
3562 s
->match_callback
.install_callback
= install_callback
;
3564 if (bus
->bus_client
) {
3565 BusMatchScope scope
;
3567 scope
= bus_match_get_scope(components
, n_components
);
3569 /* Do not install server-side matches for matches against the local service, interface or bus path. */
3570 if (scope
!= BUS_MATCH_LOCAL
) {
3572 /* We store the original match string, so that we can use it to remove the match again. */
3574 s
->match_callback
.match_string
= strdup(match
);
3575 if (!s
->match_callback
.match_string
)
3579 r
= bus_add_match_internal_async(bus
,
3580 &s
->match_callback
.install_slot
,
3581 s
->match_callback
.match_string
,
3588 /* Make the slot of the match call floating now. We need the reference, but we don't
3589 * want that this match pins the bus object, hence we first create it non-floating, but
3590 * then make it floating. */
3591 r
= sd_bus_slot_set_floating(s
->match_callback
.install_slot
, true);
3593 r
= bus_add_match_internal(bus
,
3594 s
->match_callback
.match_string
,
3596 &s
->match_callback
.after
);
3600 s
->match_added
= true;
3604 bus
->match_callbacks_modified
= true;
3605 r
= bus_match_add(&bus
->match_callbacks
, components
, n_components
, &s
->match_callback
);
3616 _public_
int sd_bus_add_match(
3618 sd_bus_slot
**ret_slot
,
3620 sd_bus_message_handler_t callback
,
3623 return bus_add_match_full(bus
, ret_slot
, false, match
, callback
, NULL
, userdata
, 0);
3626 _public_
int sd_bus_add_match_async(
3628 sd_bus_slot
**ret_slot
,
3630 sd_bus_message_handler_t callback
,
3631 sd_bus_message_handler_t install_callback
,
3634 return bus_add_match_full(bus
, ret_slot
, true, match
, callback
, install_callback
, userdata
, 0);
3637 static int io_callback(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
3638 sd_bus
*bus
= ASSERT_PTR(userdata
);
3641 /* Note that this is called both on input_fd, output_fd, as well as inotify_fd events */
3643 r
= sd_bus_process(bus
, NULL
);
3645 log_debug_errno(r
, "Processing of bus failed, closing down: %m");
3646 bus_enter_closing(bus
);
3652 static int time_callback(sd_event_source
*s
, uint64_t usec
, void *userdata
) {
3653 sd_bus
*bus
= ASSERT_PTR(userdata
);
3656 r
= sd_bus_process(bus
, NULL
);
3658 log_debug_errno(r
, "Processing of bus failed, closing down: %m");
3659 bus_enter_closing(bus
);
3665 static int prepare_callback(sd_event_source
*s
, void *userdata
) {
3666 sd_bus
*bus
= ASSERT_PTR(userdata
);
3672 e
= sd_bus_get_events(bus
);
3678 if (bus
->output_fd
!= bus
->input_fd
) {
3680 r
= sd_event_source_set_io_events(bus
->input_io_event_source
, e
& POLLIN
);
3684 r
= sd_event_source_set_io_events(bus
->output_io_event_source
, e
& POLLOUT
);
3686 r
= sd_event_source_set_io_events(bus
->input_io_event_source
, e
);
3690 r
= sd_bus_get_timeout(bus
, &until
);
3696 j
= sd_event_source_set_time(bus
->time_event_source
, until
);
3703 r
= sd_event_source_set_enabled(bus
->time_event_source
, r
> 0 ? SD_EVENT_ONESHOT
: SD_EVENT_OFF
);
3710 log_debug_errno(r
, "Preparing of bus events failed, closing down: %m");
3711 bus_enter_closing(bus
);
3716 static int quit_callback(sd_event_source
*event
, void *userdata
) {
3717 sd_bus
*bus
= userdata
;
3721 if (bus
->close_on_exit
) {
3729 int bus_attach_io_events(sd_bus
*bus
) {
3734 if (bus
->input_fd
< 0)
3740 if (!bus
->input_io_event_source
) {
3741 r
= sd_event_add_io(bus
->event
, &bus
->input_io_event_source
, bus
->input_fd
, 0, io_callback
, bus
);
3745 r
= sd_event_source_set_prepare(bus
->input_io_event_source
, prepare_callback
);
3749 r
= sd_event_source_set_priority(bus
->input_io_event_source
, bus
->event_priority
);
3753 r
= sd_event_source_set_description(bus
->input_io_event_source
, "bus-input");
3755 r
= sd_event_source_set_io_fd(bus
->input_io_event_source
, bus
->input_fd
);
3760 if (bus
->output_fd
!= bus
->input_fd
) {
3761 assert(bus
->output_fd
>= 0);
3763 if (!bus
->output_io_event_source
) {
3764 r
= sd_event_add_io(bus
->event
, &bus
->output_io_event_source
, bus
->output_fd
, 0, io_callback
, bus
);
3768 r
= sd_event_source_set_priority(bus
->output_io_event_source
, bus
->event_priority
);
3772 r
= sd_event_source_set_description(bus
->input_io_event_source
, "bus-output");
3774 r
= sd_event_source_set_io_fd(bus
->output_io_event_source
, bus
->output_fd
);
3783 static void bus_detach_io_events(sd_bus
*bus
) {
3786 bus
->input_io_event_source
= sd_event_source_disable_unref(bus
->input_io_event_source
);
3787 bus
->output_io_event_source
= sd_event_source_disable_unref(bus
->output_io_event_source
);
3790 int bus_attach_inotify_event(sd_bus
*bus
) {
3795 if (bus
->inotify_fd
< 0)
3801 if (!bus
->inotify_event_source
) {
3802 r
= sd_event_add_io(bus
->event
, &bus
->inotify_event_source
, bus
->inotify_fd
, EPOLLIN
, io_callback
, bus
);
3806 r
= sd_event_source_set_priority(bus
->inotify_event_source
, bus
->event_priority
);
3810 r
= sd_event_source_set_description(bus
->inotify_event_source
, "bus-inotify");
3812 r
= sd_event_source_set_io_fd(bus
->inotify_event_source
, bus
->inotify_fd
);
3819 _public_
int sd_bus_attach_event(sd_bus
*bus
, sd_event
*event
, int priority
) {
3822 assert_return(bus
, -EINVAL
);
3823 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
3824 assert_return(!bus
->event
, -EBUSY
);
3826 assert(!bus
->input_io_event_source
);
3827 assert(!bus
->output_io_event_source
);
3828 assert(!bus
->time_event_source
);
3831 bus
->event
= sd_event_ref(event
);
3833 r
= sd_event_default(&bus
->event
);
3838 bus
->event_priority
= priority
;
3840 r
= sd_event_add_time(bus
->event
, &bus
->time_event_source
, CLOCK_MONOTONIC
, 0, 0, time_callback
, bus
);
3844 r
= sd_event_source_set_priority(bus
->time_event_source
, priority
);
3848 r
= sd_event_source_set_description(bus
->time_event_source
, "bus-time");
3852 r
= sd_event_add_exit(bus
->event
, &bus
->quit_event_source
, quit_callback
, bus
);
3856 r
= sd_event_source_set_description(bus
->quit_event_source
, "bus-exit");
3860 r
= bus_attach_io_events(bus
);
3864 r
= bus_attach_inotify_event(bus
);
3871 sd_bus_detach_event(bus
);
3875 _public_
int sd_bus_detach_event(sd_bus
*bus
) {
3876 assert_return(bus
, -EINVAL
);
3877 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
3882 bus_detach_io_events(bus
);
3883 bus
->inotify_event_source
= sd_event_source_disable_unref(bus
->inotify_event_source
);
3884 bus
->time_event_source
= sd_event_source_disable_unref(bus
->time_event_source
);
3885 bus
->quit_event_source
= sd_event_source_disable_unref(bus
->quit_event_source
);
3887 bus
->event
= sd_event_unref(bus
->event
);
3891 _public_ sd_event
* sd_bus_get_event(sd_bus
*bus
) {
3892 assert_return(bus
= bus_resolve(bus
), NULL
);
3897 _public_ sd_bus_message
* sd_bus_get_current_message(sd_bus
*bus
) {
3898 assert_return(bus
= bus_resolve(bus
), NULL
);
3900 return bus
->current_message
;
3903 _public_ sd_bus_slot
* sd_bus_get_current_slot(sd_bus
*bus
) {
3904 assert_return(bus
= bus_resolve(bus
), NULL
);
3906 return bus
->current_slot
;
3909 _public_ sd_bus_message_handler_t
sd_bus_get_current_handler(sd_bus
*bus
) {
3910 assert_return(bus
= bus_resolve(bus
), NULL
);
3912 return bus
->current_handler
;
3915 _public_
void* sd_bus_get_current_userdata(sd_bus
*bus
) {
3916 assert_return(bus
= bus_resolve(bus
), NULL
);
3918 return bus
->current_userdata
;
3921 static int bus_default(int (*bus_open
)(sd_bus
**), sd_bus
**default_bus
, sd_bus
**ret
) {
3926 assert(default_bus
);
3929 return !!*default_bus
;
3932 *ret
= sd_bus_ref(*default_bus
);
3940 b
->default_bus_ptr
= default_bus
;
3948 _public_
int sd_bus_default_system(sd_bus
**ret
) {
3949 return bus_default(sd_bus_open_system
, &default_system_bus
, ret
);
3952 _public_
int sd_bus_default_user(sd_bus
**ret
) {
3953 return bus_default(sd_bus_open_user
, &default_user_bus
, ret
);
3956 _public_
int sd_bus_default(sd_bus
**ret
) {
3957 int (*bus_open
)(sd_bus
**) = NULL
;
3960 busp
= bus_choose_default(&bus_open
);
3961 return bus_default(bus_open
, busp
, ret
);
3964 _public_
int sd_bus_get_tid(sd_bus
*b
, pid_t
*tid
) {
3965 assert_return(b
, -EINVAL
);
3966 assert_return(tid
, -EINVAL
);
3967 assert_return(!bus_origin_changed(b
), -ECHILD
);
3975 return sd_event_get_tid(b
->event
, tid
);
3980 _public_
int sd_bus_path_encode(const char *prefix
, const char *external_id
, char **ret
) {
3981 _cleanup_free_
char *e
= NULL
;
3984 assert_return(object_path_is_valid(prefix
), -EINVAL
);
3985 assert_return(external_id
, -EINVAL
);
3986 assert_return(ret
, -EINVAL
);
3988 e
= bus_label_escape(external_id
);
3992 s
= path_join(prefix
, e
);
4000 _public_
int sd_bus_path_decode(const char *path
, const char *prefix
, char **ret
) {
4004 assert_return(object_path_is_valid(path
), -EINVAL
);
4005 assert_return(object_path_is_valid(prefix
), -EINVAL
);
4006 assert_return(ret
, -EINVAL
);
4008 e
= object_path_startswith(path
, prefix
);
4014 /* Note that 'e' might be an empty string here. That's expected. E.g. a case where the subtree
4015 * corresponds to a subtree on a disk, and we want to return something that represents the root
4016 * of the filesystem. */
4018 s
= bus_label_unescape(e
);
4026 _public_
int sd_bus_path_encode_many(char **ret
, const char *path_template
, ...) {
4027 _cleanup_strv_free_
char **labels
= NULL
;
4028 char *path
, *path_pos
, **label_pos
;
4029 const char *sep
, *template_pos
;
4034 assert_return(ret
, -EINVAL
);
4035 assert_return(path_template
, -EINVAL
);
4037 path_length
= strlen(path_template
);
4039 va_start(list
, path_template
);
4040 for (sep
= strchr(path_template
, '%'); sep
; sep
= strchr(sep
+ 1, '%')) {
4044 arg
= va_arg(list
, const char *);
4050 label
= bus_label_escape(arg
);
4056 r
= strv_consume(&labels
, label
);
4062 /* add label length, but account for the format character */
4063 path_length
+= strlen(label
) - 1;
4067 path
= malloc(path_length
+ 1);
4074 for (template_pos
= path_template
; *template_pos
; ) {
4075 sep
= strchrnul(template_pos
, '%');
4076 path_pos
= mempcpy(path_pos
, template_pos
, sep
- template_pos
);
4080 path_pos
= stpcpy(path_pos
, *label_pos
++);
4081 template_pos
= sep
+ 1;
4089 _public_
int sd_bus_path_decode_many(const char *path
, const char *path_template
, ...) {
4090 _cleanup_strv_free_
char **labels
= NULL
;
4091 const char *template_pos
, *path_pos
;
4097 * This decodes an object-path based on a template argument. The
4098 * template consists of a verbatim path, optionally including special
4101 * - Each occurrence of '%' in the template matches an arbitrary
4102 * substring of a label in the given path. At most one such
4103 * directive is allowed per label. For each such directive, the
4104 * caller must provide an output parameter (char **) via va_arg. If
4105 * NULL is passed, the given label is verified, but not returned.
4106 * For each matched label, the *decoded* label is stored in the
4107 * passed output argument, and the caller is responsible to free
4108 * it. Note that the output arguments are only modified if the
4109 * actually path matched the template. Otherwise, they're left
4112 * This function returns <0 on error, 0 if the path does not match the
4113 * template, 1 if it matched.
4116 assert_return(path
, -EINVAL
);
4117 assert_return(path_template
, -EINVAL
);
4121 for (template_pos
= path_template
; *template_pos
; ) {
4123 size_t length
, path_length
;
4126 /* verify everything until the next '%' matches verbatim */
4127 sep
= strchrnul(template_pos
, '%');
4128 length
= sep
- template_pos
;
4129 if (!strneq(path_pos
, template_pos
, length
))
4133 template_pos
+= length
;
4138 /* We found the next '%' character. Everything up until here
4139 * matched. We now skip ahead to the end of this label and make
4140 * sure it matches the tail of the label in the path. Then we
4141 * decode the string in-between and save it for later use. */
4143 ++template_pos
; /* skip over '%' */
4145 sep
= strchrnul(template_pos
, '/');
4146 length
= sep
- template_pos
; /* length of suffix to match verbatim */
4148 /* verify the suffixes match */
4149 sep
= strchrnul(path_pos
, '/');
4150 path_length
= sep
- path_pos
;
4151 if (length
> path_length
|| !strneq(sep
- length
, template_pos
, length
))
4154 template_pos
+= length
; /* skip over matched label */
4155 length
= sep
- path_pos
- length
; /* length of sub-label to decode */
4157 /* store unescaped label for later use */
4158 label
= bus_label_unescape_n(path_pos
, length
);
4162 r
= strv_consume(&labels
, label
);
4166 path_pos
= sep
; /* skip decoded label and suffix */
4169 /* end of template must match end of path */
4173 /* copy the labels over to the caller */
4174 va_start(list
, path_template
);
4175 for (label_pos
= labels
; label_pos
&& *label_pos
; ++label_pos
) {
4178 arg
= va_arg(list
, char **);
4186 labels
= mfree(labels
);
4190 _public_
int sd_bus_try_close(sd_bus
*bus
) {
4191 assert_return(bus
, -EINVAL
);
4192 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4193 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4198 _public_
int sd_bus_get_description(sd_bus
*bus
, const char **ret
) {
4199 assert_return(bus
, -EINVAL
);
4200 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4201 assert_return(ret
, -EINVAL
);
4202 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4204 const char *d
= bus
->description
;
4206 d
= runtime_scope_to_string(bus
->runtime_scope
);
4214 _public_
int sd_bus_get_scope(sd_bus
*bus
, const char **ret
) {
4215 assert_return(bus
, -EINVAL
);
4216 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4217 assert_return(ret
, -EINVAL
);
4218 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4220 if (bus
->runtime_scope
< 0)
4223 *ret
= runtime_scope_to_string(bus
->runtime_scope
);
4227 _public_
int sd_bus_get_address(sd_bus
*bus
, const char **ret
) {
4228 assert_return(bus
, -EINVAL
);
4229 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4230 assert_return(ret
, -EINVAL
);
4231 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4236 *ret
= bus
->address
;
4240 _public_
int sd_bus_get_creds_mask(sd_bus
*bus
, uint64_t *ret
) {
4241 assert_return(bus
, -EINVAL
);
4242 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4243 assert_return(ret
, -EINVAL
);
4244 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4246 *ret
= bus
->creds_mask
;
4250 _public_
int sd_bus_is_bus_client(sd_bus
*bus
) {
4251 assert_return(bus
, -EINVAL
);
4252 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4253 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4255 return bus
->bus_client
;
4258 _public_
int sd_bus_is_server(sd_bus
*bus
) {
4259 assert_return(bus
, -EINVAL
);
4260 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4261 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4263 return bus
->is_server
;
4266 _public_
int sd_bus_is_anonymous(sd_bus
*bus
) {
4267 assert_return(bus
, -EINVAL
);
4268 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4269 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4271 return bus
->anonymous_auth
;
4274 _public_
int sd_bus_is_trusted(sd_bus
*bus
) {
4275 assert_return(bus
, -EINVAL
);
4276 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4277 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4279 return bus
->trusted
;
4282 _public_
int sd_bus_is_monitor(sd_bus
*bus
) {
4283 assert_return(bus
, -EINVAL
);
4284 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4285 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4287 return bus
->is_monitor
;
4290 static void flush_close(sd_bus
*bus
) {
4294 /* Flushes and closes the specified bus. We take a ref before,
4295 * to ensure the flushing does not cause the bus to be
4298 sd_bus_flush_close_unref(sd_bus_ref(bus
));
4301 _public_
void sd_bus_default_flush_close(void) {
4302 flush_close(default_starter_bus
);
4303 flush_close(default_user_bus
);
4304 flush_close(default_system_bus
);
4307 _public_
int sd_bus_set_exit_on_disconnect(sd_bus
*bus
, int b
) {
4308 assert_return(bus
, -EINVAL
);
4309 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4311 /* Turns on exit-on-disconnect, and triggers it immediately if the bus connection was already
4312 * disconnected. Note that this is triggered exclusively on disconnections triggered by the server side, never
4313 * from the client side. */
4314 bus
->exit_on_disconnect
= b
;
4316 /* If the exit condition was triggered already, exit immediately. */
4317 return bus_exit_now(bus
, /* event= */ NULL
);
4320 _public_
int sd_bus_get_exit_on_disconnect(sd_bus
*bus
) {
4321 assert_return(bus
, -EINVAL
);
4322 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4324 return bus
->exit_on_disconnect
;
4327 _public_
int sd_bus_set_sender(sd_bus
*bus
, const char *sender
) {
4328 assert_return(bus
, -EINVAL
);
4329 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4330 assert_return(!bus
->bus_client
, -EPERM
);
4331 assert_return(!sender
|| service_name_is_valid(sender
), -EINVAL
);
4333 return free_and_strdup(&bus
->patch_sender
, sender
);
4336 _public_
int sd_bus_get_sender(sd_bus
*bus
, const char **ret
) {
4337 assert_return(bus
, -EINVAL
);
4338 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4339 assert_return(ret
, -EINVAL
);
4341 if (!bus
->patch_sender
)
4344 *ret
= bus
->patch_sender
;
4348 _public_
int sd_bus_get_n_queued_read(sd_bus
*bus
, uint64_t *ret
) {
4349 assert_return(bus
, -EINVAL
);
4350 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4351 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4352 assert_return(ret
, -EINVAL
);
4354 *ret
= bus
->rqueue_size
;
4358 _public_
int sd_bus_get_n_queued_write(sd_bus
*bus
, uint64_t *ret
) {
4359 assert_return(bus
, -EINVAL
);
4360 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4361 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4362 assert_return(ret
, -EINVAL
);
4364 *ret
= bus
->wqueue_size
;
4368 _public_
int sd_bus_set_method_call_timeout(sd_bus
*bus
, uint64_t usec
) {
4369 assert_return(bus
, -EINVAL
);
4370 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4372 bus
->method_call_timeout
= usec
;
4376 _public_
int sd_bus_get_method_call_timeout(sd_bus
*bus
, uint64_t *ret
) {
4380 assert_return(bus
, -EINVAL
);
4381 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4382 assert_return(ret
, -EINVAL
);
4384 if (bus
->method_call_timeout
!= 0) {
4385 *ret
= bus
->method_call_timeout
;
4389 e
= secure_getenv("SYSTEMD_BUS_TIMEOUT");
4390 if (e
&& parse_sec(e
, &usec
) >= 0 && usec
!= 0) {
4391 /* Save the parsed value to avoid multiple parsing. To change the timeout value,
4392 * use sd_bus_set_method_call_timeout() instead of setenv(). */
4393 *ret
= bus
->method_call_timeout
= usec
;
4397 *ret
= bus
->method_call_timeout
= BUS_DEFAULT_TIMEOUT
;
4401 _public_
int sd_bus_set_close_on_exit(sd_bus
*bus
, int b
) {
4402 assert_return(bus
, -EINVAL
);
4403 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4405 bus
->close_on_exit
= b
;
4409 _public_
int sd_bus_get_close_on_exit(sd_bus
*bus
) {
4410 assert_return(bus
, -EINVAL
);
4411 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4413 return bus
->close_on_exit
;
4416 _public_
int sd_bus_enqueue_for_read(sd_bus
*bus
, sd_bus_message
*m
) {
4419 assert_return(bus
, -EINVAL
);
4420 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4421 assert_return(m
, -EINVAL
);
4422 assert_return(m
->sealed
, -EINVAL
);
4423 assert_return(!bus_origin_changed(bus
), -ECHILD
);
4425 if (!BUS_IS_OPEN(bus
->state
))
4428 /* Re-enqueue a message for reading. This is primarily useful for PolicyKit-style authentication,
4429 * where we accept a message, then determine we need to interactively authenticate the user, and then
4430 * we want to process the message again. */
4432 r
= bus_rqueue_make_room(bus
);
4436 bus
->rqueue
[bus
->rqueue_size
++] = bus_message_ref_queued(m
, bus
);
4440 _public_
int sd_bus_pending_method_calls(sd_bus
*bus
) {
4442 /* Returns the number of currently pending asynchronous method calls. This is graceful, i.e. an
4443 * unallocated (i.e. NULL) bus connection has no method calls pending. */
4448 assert_return(bus
= bus_resolve(bus
), -ENOPKG
);
4450 if (!BUS_IS_OPEN(bus
->state
))
4453 size_t n
= ordered_hashmap_size(bus
->reply_callbacks
);
4455 return n
> INT_MAX
? INT_MAX
: (int) n
; /* paranoid overflow check */