1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2013 Lennart Poettering
15 //#include <sys/wait.h>
20 #include "alloc-util.h"
21 #include "bus-container.h"
22 #include "bus-control.h"
23 #include "bus-internal.h"
24 #include "bus-kernel.h"
25 #include "bus-label.h"
26 #include "bus-message.h"
27 #include "bus-objects.h"
28 #include "bus-protocol.h"
30 #include "bus-socket.h"
31 #include "bus-track.h"
34 #include "cgroup-util.h"
37 #include "hexdecoct.h"
38 #include "hostname-util.h"
41 #include "parse-util.h"
42 //#include "process-util.h"
43 #include "string-util.h"
47 /// Additional includes needed by elogind
48 #include "process-util.h"
50 #define log_debug_bus_message(m) \
52 sd_bus_message *_mm = (m); \
53 log_debug("Got message type=%s sender=%s destination=%s path=%s interface=%s member=%s cookie=%" PRIu64 " reply_cookie=%" PRIu64 " signature=%s error-name=%s error-message=%s", \
54 bus_message_type_to_string(_mm->header->type), \
55 strna(sd_bus_message_get_sender(_mm)), \
56 strna(sd_bus_message_get_destination(_mm)), \
57 strna(sd_bus_message_get_path(_mm)), \
58 strna(sd_bus_message_get_interface(_mm)), \
59 strna(sd_bus_message_get_member(_mm)), \
60 BUS_MESSAGE_COOKIE(_mm), \
62 strna(_mm->root_container.signature), \
63 strna(_mm->error.name), \
64 strna(_mm->error.message)); \
67 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec);
68 static void bus_detach_io_events(sd_bus *b);
69 static void bus_detach_inotify_event(sd_bus *b);
71 static thread_local sd_bus *default_system_bus = NULL;
72 static thread_local sd_bus *default_user_bus = NULL;
73 static thread_local sd_bus *default_starter_bus = NULL;
75 static sd_bus **bus_choose_default(int (**bus_open)(sd_bus **)) {
78 /* Let's try our best to reuse another cached connection. If
79 * the starter bus type is set, connect via our normal
80 * connection logic, ignoring $DBUS_STARTER_ADDRESS, so that
81 * we can share the connection with the user/system default
84 e = secure_getenv("DBUS_STARTER_BUS_TYPE");
86 if (streq(e, "system")) {
88 *bus_open = sd_bus_open_system;
89 return &default_system_bus;
90 } else if (STR_IN_SET(e, "user", "session")) {
92 *bus_open = sd_bus_open_user;
93 return &default_user_bus;
97 /* No type is specified, so we have not other option than to
98 * use the starter address if it is set. */
99 e = secure_getenv("DBUS_STARTER_ADDRESS");
102 *bus_open = sd_bus_open;
103 return &default_starter_bus;
106 /* Finally, if nothing is set use the cached connection for
109 if (cg_pid_get_owner_uid(0, NULL) >= 0) {
111 *bus_open = sd_bus_open_user;
112 return &default_user_bus;
115 *bus_open = sd_bus_open_system;
116 return &default_system_bus;
120 sd_bus *bus_resolve(sd_bus *bus) {
121 switch ((uintptr_t) bus) {
122 case (uintptr_t) SD_BUS_DEFAULT:
123 return *(bus_choose_default(NULL));
124 case (uintptr_t) SD_BUS_DEFAULT_USER:
125 return default_user_bus;
126 case (uintptr_t) SD_BUS_DEFAULT_SYSTEM:
127 return default_system_bus;
133 void bus_close_io_fds(sd_bus *b) {
136 bus_detach_io_events(b);
138 if (b->input_fd != b->output_fd)
139 safe_close(b->output_fd);
140 b->output_fd = b->input_fd = safe_close(b->input_fd);
143 void bus_close_inotify_fd(sd_bus *b) {
146 bus_detach_inotify_event(b);
148 b->inotify_fd = safe_close(b->inotify_fd);
149 b->inotify_watches = mfree(b->inotify_watches);
150 b->n_inotify_watches = 0;
153 static void bus_reset_queues(sd_bus *b) {
156 while (b->rqueue_size > 0)
157 sd_bus_message_unref(b->rqueue[--b->rqueue_size]);
159 b->rqueue = mfree(b->rqueue);
160 b->rqueue_allocated = 0;
162 while (b->wqueue_size > 0)
163 sd_bus_message_unref(b->wqueue[--b->wqueue_size]);
165 b->wqueue = mfree(b->wqueue);
166 b->wqueue_allocated = 0;
169 static sd_bus* bus_free(sd_bus *b) {
173 assert(!b->track_queue);
176 b->state = BUS_CLOSED;
178 sd_bus_detach_event(b);
180 while ((s = b->slots)) {
181 /* At this point only floating slots can still be
182 * around, because the non-floating ones keep a
183 * reference to the bus, and we thus couldn't be
184 * destructing right now... We forcibly disconnect the
185 * slots here, so that they still can be referenced by
186 * apps, but are dead. */
189 bus_slot_disconnect(s);
190 sd_bus_slot_unref(s);
193 if (b->default_bus_ptr)
194 *b->default_bus_ptr = NULL;
197 bus_close_inotify_fd(b);
202 free(b->unique_name);
203 free(b->auth_buffer);
206 free(b->cgroup_root);
207 free(b->description);
208 free(b->patch_sender);
211 strv_free(b->exec_argv);
213 close_many(b->fds, b->n_fds);
218 ordered_hashmap_free_free(b->reply_callbacks);
219 prioq_free(b->reply_callbacks_prioq);
221 assert(b->match_callbacks.type == BUS_MATCH_ROOT);
222 bus_match_free(&b->match_callbacks);
224 hashmap_free_free(b->vtable_methods);
225 hashmap_free_free(b->vtable_properties);
227 assert(hashmap_isempty(b->nodes));
228 hashmap_free(b->nodes);
232 assert_se(pthread_mutex_destroy(&b->memfd_cache_mutex) == 0);
237 DEFINE_TRIVIAL_CLEANUP_FUNC(sd_bus*, bus_free);
239 _public_ int sd_bus_new(sd_bus **ret) {
240 _cleanup_free_ sd_bus *b = NULL;
242 assert_return(ret, -EINVAL);
248 b->n_ref = REFCNT_INIT;
249 b->input_fd = b->output_fd = -1;
251 b->message_version = 1;
252 b->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
254 b->original_pid = getpid_cached();
255 b->n_groups = (size_t) -1;
257 assert_se(pthread_mutex_init(&b->memfd_cache_mutex, NULL) == 0);
259 /* We guarantee that wqueue always has space for at least one entry */
260 if (!GREEDY_REALLOC(b->wqueue, b->wqueue_allocated, 1))
267 _public_ int sd_bus_set_address(sd_bus *bus, const char *address) {
268 assert_return(bus, -EINVAL);
269 assert_return(bus = bus_resolve(bus), -ENOPKG);
270 assert_return(bus->state == BUS_UNSET, -EPERM);
271 assert_return(address, -EINVAL);
272 assert_return(!bus_pid_changed(bus), -ECHILD);
274 return free_and_strdup(&bus->address, address);
277 _public_ int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd) {
278 assert_return(bus, -EINVAL);
279 assert_return(bus = bus_resolve(bus), -ENOPKG);
280 assert_return(bus->state == BUS_UNSET, -EPERM);
281 assert_return(input_fd >= 0, -EBADF);
282 assert_return(output_fd >= 0, -EBADF);
283 assert_return(!bus_pid_changed(bus), -ECHILD);
285 bus->input_fd = input_fd;
286 bus->output_fd = output_fd;
290 _public_ int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]) {
291 _cleanup_strv_free_ char **a = NULL;
294 assert_return(bus, -EINVAL);
295 assert_return(bus = bus_resolve(bus), -ENOPKG);
296 assert_return(bus->state == BUS_UNSET, -EPERM);
297 assert_return(path, -EINVAL);
298 assert_return(!strv_isempty(argv), -EINVAL);
299 assert_return(!bus_pid_changed(bus), -ECHILD);
305 r = free_and_strdup(&bus->exec_path, path);
309 return strv_free_and_replace(bus->exec_argv, a);
312 _public_ int sd_bus_set_bus_client(sd_bus *bus, int b) {
313 assert_return(bus, -EINVAL);
314 assert_return(bus = bus_resolve(bus), -ENOPKG);
315 assert_return(bus->state == BUS_UNSET, -EPERM);
316 assert_return(!bus->patch_sender, -EPERM);
317 assert_return(!bus_pid_changed(bus), -ECHILD);
319 bus->bus_client = !!b;
323 _public_ int sd_bus_set_monitor(sd_bus *bus, int b) {
324 assert_return(bus, -EINVAL);
325 assert_return(bus = bus_resolve(bus), -ENOPKG);
326 assert_return(bus->state == BUS_UNSET, -EPERM);
327 assert_return(!bus_pid_changed(bus), -ECHILD);
329 bus->is_monitor = !!b;
333 _public_ int sd_bus_negotiate_fds(sd_bus *bus, int b) {
334 assert_return(bus, -EINVAL);
335 assert_return(bus = bus_resolve(bus), -ENOPKG);
336 assert_return(bus->state == BUS_UNSET, -EPERM);
337 assert_return(!bus_pid_changed(bus), -ECHILD);
339 bus->accept_fd = !!b;
343 _public_ int sd_bus_negotiate_timestamp(sd_bus *bus, int b) {
344 assert_return(bus, -EINVAL);
345 assert_return(bus = bus_resolve(bus), -ENOPKG);
346 assert_return(!IN_SET(bus->state, BUS_CLOSING, BUS_CLOSED), -EPERM);
347 assert_return(!bus_pid_changed(bus), -ECHILD);
349 /* This is not actually supported by any of our transports these days, but we do honour it for synthetic
350 * replies, and maybe one day classic D-Bus learns this too */
351 bus->attach_timestamp = !!b;
356 _public_ int sd_bus_negotiate_creds(sd_bus *bus, int b, uint64_t mask) {
357 assert_return(bus, -EINVAL);
358 assert_return(bus = bus_resolve(bus), -ENOPKG);
359 assert_return(mask <= _SD_BUS_CREDS_ALL, -EINVAL);
360 assert_return(!IN_SET(bus->state, BUS_CLOSING, BUS_CLOSED), -EPERM);
361 assert_return(!bus_pid_changed(bus), -ECHILD);
363 SET_FLAG(bus->creds_mask, mask, b);
365 /* The well knowns we need unconditionally, so that matches can work */
366 bus->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
371 _public_ int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id) {
372 assert_return(bus, -EINVAL);
373 assert_return(bus = bus_resolve(bus), -ENOPKG);
374 assert_return(b || sd_id128_equal(server_id, SD_ID128_NULL), -EINVAL);
375 assert_return(bus->state == BUS_UNSET, -EPERM);
376 assert_return(!bus_pid_changed(bus), -ECHILD);
378 bus->is_server = !!b;
379 bus->server_id = server_id;
383 _public_ int sd_bus_set_anonymous(sd_bus *bus, int b) {
384 assert_return(bus, -EINVAL);
385 assert_return(bus = bus_resolve(bus), -ENOPKG);
386 assert_return(bus->state == BUS_UNSET, -EPERM);
387 assert_return(!bus_pid_changed(bus), -ECHILD);
389 bus->anonymous_auth = !!b;
393 _public_ int sd_bus_set_trusted(sd_bus *bus, int b) {
394 assert_return(bus, -EINVAL);
395 assert_return(bus = bus_resolve(bus), -ENOPKG);
396 assert_return(bus->state == BUS_UNSET, -EPERM);
397 assert_return(!bus_pid_changed(bus), -ECHILD);
403 _public_ int sd_bus_set_description(sd_bus *bus, const char *description) {
404 assert_return(bus, -EINVAL);
405 assert_return(bus = bus_resolve(bus), -ENOPKG);
406 assert_return(bus->state == BUS_UNSET, -EPERM);
407 assert_return(!bus_pid_changed(bus), -ECHILD);
409 return free_and_strdup(&bus->description, description);
412 _public_ int sd_bus_set_allow_interactive_authorization(sd_bus *bus, int b) {
413 assert_return(bus, -EINVAL);
414 assert_return(bus = bus_resolve(bus), -ENOPKG);
415 assert_return(!bus_pid_changed(bus), -ECHILD);
417 bus->allow_interactive_authorization = !!b;
421 _public_ int sd_bus_get_allow_interactive_authorization(sd_bus *bus) {
422 assert_return(bus, -EINVAL);
423 assert_return(bus = bus_resolve(bus), -ENOPKG);
424 assert_return(!bus_pid_changed(bus), -ECHILD);
426 return bus->allow_interactive_authorization;
429 _public_ int sd_bus_set_watch_bind(sd_bus *bus, int b) {
430 assert_return(bus, -EINVAL);
431 assert_return(bus = bus_resolve(bus), -ENOPKG);
432 assert_return(bus->state == BUS_UNSET, -EPERM);
433 assert_return(!bus_pid_changed(bus), -ECHILD);
435 bus->watch_bind = !!b;
439 _public_ int sd_bus_get_watch_bind(sd_bus *bus) {
440 assert_return(bus, -EINVAL);
441 assert_return(bus = bus_resolve(bus), -ENOPKG);
442 assert_return(!bus_pid_changed(bus), -ECHILD);
444 return bus->watch_bind;
447 _public_ int sd_bus_set_connected_signal(sd_bus *bus, int b) {
448 assert_return(bus, -EINVAL);
449 assert_return(bus = bus_resolve(bus), -ENOPKG);
450 assert_return(bus->state == BUS_UNSET, -EPERM);
451 assert_return(!bus_pid_changed(bus), -ECHILD);
453 bus->connected_signal = !!b;
457 _public_ int sd_bus_get_connected_signal(sd_bus *bus) {
458 assert_return(bus, -EINVAL);
459 assert_return(bus = bus_resolve(bus), -ENOPKG);
460 assert_return(!bus_pid_changed(bus), -ECHILD);
462 return bus->connected_signal;
465 static int synthesize_connected_signal(sd_bus *bus) {
466 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
471 /* If enabled, synthesizes a local "Connected" signal mirroring the local "Disconnected" signal. This is called
472 * whenever we fully established a connection, i.e. after the authorization phase, and after receiving the
473 * Hello() reply. Or in other words, whenver we enter BUS_RUNNING state.
475 * This is useful so that clients can start doing stuff whenver the connection is fully established in a way
476 * that works independently from whether we connected to a full bus or just a direct connection. */
478 if (!bus->connected_signal)
481 r = sd_bus_message_new_signal(
484 "/org/freedesktop/DBus/Local",
485 "org.freedesktop.DBus.Local",
490 bus_message_set_sender_local(bus, m);
492 r = bus_seal_synthetic_message(bus, m);
496 r = bus_rqueue_make_room(bus);
500 /* Insert at the very front */
501 memmove(bus->rqueue + 1, bus->rqueue, sizeof(sd_bus_message*) * bus->rqueue_size);
502 bus->rqueue[0] = TAKE_PTR(m);
508 void bus_set_state(sd_bus *bus, enum bus_state state) {
510 static const char * const table[_BUS_STATE_MAX] = {
511 [BUS_UNSET] = "UNSET",
512 [BUS_WATCH_BIND] = "WATCH_BIND",
513 [BUS_OPENING] = "OPENING",
514 [BUS_AUTHENTICATING] = "AUTHENTICATING",
515 [BUS_HELLO] = "HELLO",
516 [BUS_RUNNING] = "RUNNING",
517 [BUS_CLOSING] = "CLOSING",
518 [BUS_CLOSED] = "CLOSED",
522 assert(state < _BUS_STATE_MAX);
524 if (state == bus->state)
527 log_debug("Bus %s: changing state %s → %s", strna(bus->description), table[bus->state], table[state]);
531 static int hello_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
539 assert(IN_SET(bus->state, BUS_HELLO, BUS_CLOSING));
541 r = sd_bus_message_get_errno(reply);
545 r = sd_bus_message_read(reply, "s", &s);
549 if (!service_name_is_valid(s) || s[0] != ':')
552 r = free_and_strdup(&bus->unique_name, s);
556 if (bus->state == BUS_HELLO) {
557 bus_set_state(bus, BUS_RUNNING);
559 r = synthesize_connected_signal(bus);
567 static int bus_send_hello(sd_bus *bus) {
568 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
573 if (!bus->bus_client)
576 r = sd_bus_message_new_method_call(
579 "org.freedesktop.DBus",
580 "/org/freedesktop/DBus",
581 "org.freedesktop.DBus",
586 return sd_bus_call_async(bus, NULL, m, hello_callback, NULL, 0);
589 int bus_start_running(sd_bus *bus) {
590 struct reply_callback *c;
596 assert(bus->state < BUS_HELLO);
598 /* We start all method call timeouts when we enter BUS_HELLO or BUS_RUNNING mode. At this point let's convert
599 * all relative to absolute timestamps. Note that we do not reshuffle the reply callback priority queue since
600 * adding a fixed value to all entries should not alter the internal order. */
602 n = now(CLOCK_MONOTONIC);
603 ORDERED_HASHMAP_FOREACH(c, bus->reply_callbacks, i) {
604 if (c->timeout_usec == 0)
607 c->timeout_usec = usec_add(n, c->timeout_usec);
610 if (bus->bus_client) {
611 bus_set_state(bus, BUS_HELLO);
615 bus_set_state(bus, BUS_RUNNING);
617 r = synthesize_connected_signal(bus);
624 static int parse_address_key(const char **p, const char *key, char **value) {
625 size_t l, n = 0, allocated = 0;
626 _cleanup_free_ char *r = NULL;
635 if (strncmp(*p, key, l) != 0)
648 while (!IN_SET(*a, ';', ',', 0)) {
662 c = (char) ((x << 4) | y);
669 if (!GREEDY_REALLOC(r, allocated, n + 2))
687 free_and_replace(*value, r);
692 static void skip_address_key(const char **p) {
696 *p += strcspn(*p, ",");
702 static int parse_unix_address(sd_bus *b, const char **p, char **guid) {
703 _cleanup_free_ char *path = NULL, *abstract = NULL;
712 while (!IN_SET(**p, 0, ';')) {
713 r = parse_address_key(p, "guid", guid);
719 r = parse_address_key(p, "path", &path);
725 r = parse_address_key(p, "abstract", &abstract);
734 if (!path && !abstract)
737 if (path && abstract)
742 if (l > sizeof(b->sockaddr.un.sun_path))
745 b->sockaddr.un.sun_family = AF_UNIX;
746 strncpy(b->sockaddr.un.sun_path, path, sizeof(b->sockaddr.un.sun_path));
747 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l;
748 } else if (abstract) {
749 l = strlen(abstract);
750 if (l > sizeof(b->sockaddr.un.sun_path) - 1)
753 b->sockaddr.un.sun_family = AF_UNIX;
754 b->sockaddr.un.sun_path[0] = 0;
755 strncpy(b->sockaddr.un.sun_path+1, abstract, sizeof(b->sockaddr.un.sun_path)-1);
756 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
764 static int parse_tcp_address(sd_bus *b, const char **p, char **guid) {
765 _cleanup_free_ char *host = NULL, *port = NULL, *family = NULL;
767 struct addrinfo *result, hints = {
768 .ai_socktype = SOCK_STREAM,
769 .ai_flags = AI_ADDRCONFIG,
777 while (!IN_SET(**p, 0, ';')) {
778 r = parse_address_key(p, "guid", guid);
784 r = parse_address_key(p, "host", &host);
790 r = parse_address_key(p, "port", &port);
796 r = parse_address_key(p, "family", &family);
809 if (streq(family, "ipv4"))
810 hints.ai_family = AF_INET;
811 else if (streq(family, "ipv6"))
812 hints.ai_family = AF_INET6;
817 r = getaddrinfo(host, port, &hints, &result);
821 return -EADDRNOTAVAIL;
823 memcpy(&b->sockaddr, result->ai_addr, result->ai_addrlen);
824 b->sockaddr_size = result->ai_addrlen;
826 freeaddrinfo(result);
833 static int parse_exec_address(sd_bus *b, const char **p, char **guid) {
835 unsigned n_argv = 0, j;
837 size_t allocated = 0;
845 while (!IN_SET(**p, 0, ';')) {
846 r = parse_address_key(p, "guid", guid);
852 r = parse_address_key(p, "path", &path);
858 if (startswith(*p, "argv")) {
862 ul = strtoul(*p + 4, (char**) p, 10);
863 if (errno > 0 || **p != '=' || ul > 256) {
871 if (!GREEDY_REALLOC0(argv, allocated, ul + 2)) {
879 r = parse_address_key(p, NULL, argv + ul);
894 /* Make sure there are no holes in the array, with the
895 * exception of argv[0] */
896 for (j = 1; j < n_argv; j++)
902 if (argv && argv[0] == NULL) {
903 argv[0] = strdup(path);
918 for (j = 0; j < n_argv; j++)
926 static int parse_container_unix_address(sd_bus *b, const char **p, char **guid) {
927 _cleanup_free_ char *machine = NULL, *pid = NULL;
935 while (!IN_SET(**p, 0, ';')) {
936 r = parse_address_key(p, "guid", guid);
942 r = parse_address_key(p, "machine", &machine);
948 r = parse_address_key(p, "pid", &pid);
957 if (!machine == !pid)
961 if (!machine_name_is_valid(machine))
964 free_and_replace(b->machine, machine);
966 b->machine = mfree(b->machine);
970 r = parse_pid(pid, &b->nspid);
976 b->sockaddr.un.sun_family = AF_UNIX;
977 /* Note that we use the old /var/run prefix here, to increase compatibility with really old containers */
978 strncpy(b->sockaddr.un.sun_path, "/var/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
979 b->sockaddr_size = SOCKADDR_UN_LEN(b->sockaddr.un);
985 static void bus_reset_parsed_address(sd_bus *b) {
989 b->sockaddr_size = 0;
990 b->exec_argv = strv_free(b->exec_argv);
991 b->exec_path = mfree(b->exec_path);
992 b->server_id = SD_ID128_NULL;
993 b->machine = mfree(b->machine);
997 static int bus_parse_next_address(sd_bus *b) {
998 _cleanup_free_ char *guid = NULL;
1006 if (b->address[b->address_index] == 0)
1009 bus_reset_parsed_address(b);
1011 a = b->address + b->address_index;
1020 if (startswith(a, "unix:")) {
1023 r = parse_unix_address(b, &a, &guid);
1028 } else if (startswith(a, "tcp:")) {
1031 r = parse_tcp_address(b, &a, &guid);
1037 } else if (startswith(a, "unixexec:")) {
1040 r = parse_exec_address(b, &a, &guid);
1046 } else if (startswith(a, "x-machine-unix:")) {
1049 r = parse_container_unix_address(b, &a, &guid);
1062 r = sd_id128_from_string(guid, &b->server_id);
1067 b->address_index = a - b->address;
1071 static void bus_kill_exec(sd_bus *bus) {
1072 if (pid_is_valid(bus->busexec_pid) > 0) {
1073 sigterm_wait(bus->busexec_pid);
1074 bus->busexec_pid = 0;
1078 static int bus_start_address(sd_bus *b) {
1084 bus_close_io_fds(b);
1085 bus_close_inotify_fd(b);
1089 /* If you provide multiple different bus-addresses, we
1090 * try all of them in order and use the first one that
1094 r = bus_socket_exec(b);
1095 else if ((b->nspid > 0 || b->machine) && b->sockaddr.sa.sa_family != AF_UNSPEC)
1096 r = bus_container_connect_socket(b);
1097 else if (b->sockaddr.sa.sa_family != AF_UNSPEC)
1098 r = bus_socket_connect(b);
1105 q = bus_attach_io_events(b);
1109 q = bus_attach_inotify_event(b);
1116 b->last_connect_error = -r;
1119 r = bus_parse_next_address(b);
1123 return b->last_connect_error > 0 ? -b->last_connect_error : -ECONNREFUSED;
1127 int bus_next_address(sd_bus *b) {
1130 bus_reset_parsed_address(b);
1131 return bus_start_address(b);
1134 static int bus_start_fd(sd_bus *b) {
1139 assert(b->input_fd >= 0);
1140 assert(b->output_fd >= 0);
1142 r = fd_nonblock(b->input_fd, true);
1146 r = fd_cloexec(b->input_fd, true);
1150 if (b->input_fd != b->output_fd) {
1151 r = fd_nonblock(b->output_fd, true);
1155 r = fd_cloexec(b->output_fd, true);
1160 if (fstat(b->input_fd, &st) < 0)
1163 return bus_socket_take_fd(b);
1166 _public_ int sd_bus_start(sd_bus *bus) {
1169 assert_return(bus, -EINVAL);
1170 assert_return(bus = bus_resolve(bus), -ENOPKG);
1171 assert_return(bus->state == BUS_UNSET, -EPERM);
1172 assert_return(!bus_pid_changed(bus), -ECHILD);
1174 bus_set_state(bus, BUS_OPENING);
1176 if (bus->is_server && bus->bus_client)
1179 if (bus->input_fd >= 0)
1180 r = bus_start_fd(bus);
1181 else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->machine)
1182 r = bus_start_address(bus);
1191 return bus_send_hello(bus);
1194 _public_ int sd_bus_open_with_description(sd_bus **ret, const char *description) {
1196 _cleanup_(bus_freep) sd_bus *b = NULL;
1199 assert_return(ret, -EINVAL);
1201 /* Let's connect to the starter bus if it is set, and
1202 * otherwise to the bus that is appropropriate for the scope
1203 * we are running in */
1205 e = secure_getenv("DBUS_STARTER_BUS_TYPE");
1207 if (streq(e, "system"))
1208 return sd_bus_open_system_with_description(ret, description);
1209 #if 0 /// elogind does not support systemd user instances
1210 else if (STR_IN_SET(e, "session", "user"))
1212 return sd_bus_open_user_with_description(ret, description);
1215 e = secure_getenv("DBUS_STARTER_ADDRESS");
1217 #if 0 /// elogind does not support systemd user instances
1218 if (cg_pid_get_owner_uid(0, NULL) >= 0)
1219 return sd_bus_open_user_with_description(ret, description);
1222 return sd_bus_open_system_with_description(ret, description);
1229 r = sd_bus_set_address(b, e);
1233 b->bus_client = true;
1235 /* We don't know whether the bus is trusted or not, so better
1236 * be safe, and authenticate everything */
1238 b->is_local = false;
1239 b->creds_mask |= SD_BUS_CREDS_UID | SD_BUS_CREDS_EUID | SD_BUS_CREDS_EFFECTIVE_CAPS;
1241 r = sd_bus_start(b);
1249 _public_ int sd_bus_open(sd_bus **ret) {
1250 return sd_bus_open_with_description(ret, NULL);
1253 int bus_set_address_system(sd_bus *b) {
1257 e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1259 return sd_bus_set_address(b, e);
1261 return sd_bus_set_address(b, DEFAULT_SYSTEM_BUS_ADDRESS);
1264 _public_ int sd_bus_open_system_with_description(sd_bus **ret, const char *description) {
1265 _cleanup_(bus_freep) sd_bus *b = NULL;
1268 assert_return(ret, -EINVAL);
1275 r = sd_bus_set_description(b, description);
1280 r = bus_set_address_system(b);
1284 b->bus_client = true;
1285 b->is_system = true;
1287 /* Let's do per-method access control on the system bus. We
1288 * need the caller's UID and capability set for that. */
1290 b->creds_mask |= SD_BUS_CREDS_UID | SD_BUS_CREDS_EUID | SD_BUS_CREDS_EFFECTIVE_CAPS;
1293 r = sd_bus_start(b);
1301 _public_ int sd_bus_open_system(sd_bus **ret) {
1302 return sd_bus_open_system_with_description(ret, NULL);
1305 #if 0 /// elogind can not open/use a user bus
1306 int bus_set_address_user(sd_bus *b) {
1308 _cleanup_free_ char *ee = NULL, *s = NULL;
1312 e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
1314 return sd_bus_set_address(b, e);
1316 e = secure_getenv("XDG_RUNTIME_DIR");
1320 ee = bus_address_escape(e);
1324 if (asprintf(&s, DEFAULT_USER_BUS_ADDRESS_FMT, ee) < 0)
1327 b->address = TAKE_PTR(s);
1333 _public_ int sd_bus_open_user_with_description(sd_bus **ret, const char *description) {
1334 #if 0 /// elogind does not support user buses
1335 _cleanup_(bus_freep) sd_bus *b = NULL;
1338 assert_return(ret, -EINVAL);
1345 r = sd_bus_set_description(b, description);
1350 r = bus_set_address_user(b);
1354 b->bus_client = true;
1357 /* We don't do any per-method access control on the user
1362 r = sd_bus_start(b);
1370 _public_ int sd_bus_open_user(sd_bus **ret) {
1371 return sd_bus_open_user_with_description(ret, NULL);
1373 return sd_bus_open_system(ret);
1377 int bus_set_address_system_remote(sd_bus *b, const char *host) {
1378 _cleanup_free_ char *e = NULL;
1379 char *m = NULL, *c = NULL, *a;
1384 /* Let's see if we shall enter some container */
1385 m = strchr(host, ':');
1389 /* Let's make sure this is not a port of some kind,
1390 * and is a valid machine name. */
1391 if (!in_charset(m, DIGITS) && machine_name_is_valid(m)) {
1394 /* Cut out the host part */
1395 t = strndupa(host, m - host - 1);
1396 e = bus_address_escape(t);
1400 c = strjoina(",argv5=--machine=", m);
1405 e = bus_address_escape(host);
1410 a = strjoin("unixexec:path=ssh,argv1=-xT,argv2=--,argv3=", e, ",argv4=elogind-stdio-bridge", c);
1414 return free_and_replace(b->address, a);
1417 _public_ int sd_bus_open_system_remote(sd_bus **ret, const char *host) {
1418 _cleanup_(bus_freep) sd_bus *b = NULL;
1421 assert_return(host, -EINVAL);
1422 assert_return(ret, -EINVAL);
1428 r = bus_set_address_system_remote(b, host);
1432 b->bus_client = true;
1434 b->is_system = true;
1435 b->is_local = false;
1437 r = sd_bus_start(b);
1445 int bus_set_address_system_machine(sd_bus *b, const char *machine) {
1446 _cleanup_free_ char *e = NULL;
1452 e = bus_address_escape(machine);
1456 a = strjoin("x-machine-unix:machine=", e);
1460 return free_and_replace(b->address, a);
1463 _public_ int sd_bus_open_system_machine(sd_bus **ret, const char *machine) {
1464 _cleanup_(bus_freep) sd_bus *b = NULL;
1467 assert_return(machine, -EINVAL);
1468 assert_return(ret, -EINVAL);
1469 assert_return(machine_name_is_valid(machine), -EINVAL);
1475 r = bus_set_address_system_machine(b, machine);
1479 b->bus_client = true;
1481 b->is_system = true;
1482 b->is_local = false;
1484 r = sd_bus_start(b);
1492 _public_ void sd_bus_close(sd_bus *bus) {
1495 if (bus->state == BUS_CLOSED)
1497 if (bus_pid_changed(bus))
1500 /* Don't leave ssh hanging around */
1503 bus_set_state(bus, BUS_CLOSED);
1505 sd_bus_detach_event(bus);
1507 /* Drop all queued messages so that they drop references to
1508 * the bus object and the bus may be freed */
1509 bus_reset_queues(bus);
1511 bus_close_io_fds(bus);
1512 bus_close_inotify_fd(bus);
1515 _public_ sd_bus* sd_bus_flush_close_unref(sd_bus *bus) {
1519 /* Have to do this before flush() to prevent hang */
1525 return sd_bus_unref(bus);
1528 void bus_enter_closing(sd_bus *bus) {
1531 if (!IN_SET(bus->state, BUS_WATCH_BIND, BUS_OPENING, BUS_AUTHENTICATING, BUS_HELLO, BUS_RUNNING))
1534 bus_set_state(bus, BUS_CLOSING);
1537 _public_ sd_bus *sd_bus_ref(sd_bus *bus) {
1541 assert_se(REFCNT_INC(bus->n_ref) >= 2);
1546 _public_ sd_bus *sd_bus_unref(sd_bus *bus) {
1552 i = REFCNT_DEC(bus->n_ref);
1556 return bus_free(bus);
1559 _public_ int sd_bus_is_open(sd_bus *bus) {
1560 assert_return(bus, -EINVAL);
1561 assert_return(bus = bus_resolve(bus), -ENOPKG);
1562 assert_return(!bus_pid_changed(bus), -ECHILD);
1564 return BUS_IS_OPEN(bus->state);
1567 _public_ int sd_bus_is_ready(sd_bus *bus) {
1568 assert_return(bus, -EINVAL);
1569 assert_return(bus = bus_resolve(bus), -ENOPKG);
1570 assert_return(!bus_pid_changed(bus), -ECHILD);
1572 return bus->state == BUS_RUNNING;
1575 _public_ int sd_bus_can_send(sd_bus *bus, char type) {
1578 assert_return(bus, -EINVAL);
1579 assert_return(bus = bus_resolve(bus), -ENOPKG);
1580 assert_return(bus->state != BUS_UNSET, -ENOTCONN);
1581 assert_return(!bus_pid_changed(bus), -ECHILD);
1583 if (bus->is_monitor)
1586 if (type == SD_BUS_TYPE_UNIX_FD) {
1587 if (!bus->accept_fd)
1590 r = bus_ensure_running(bus);
1594 return bus->can_fds;
1597 return bus_type_is_valid(type);
1600 _public_ int sd_bus_get_bus_id(sd_bus *bus, sd_id128_t *id) {
1603 assert_return(bus, -EINVAL);
1604 assert_return(bus = bus_resolve(bus), -ENOPKG);
1605 assert_return(id, -EINVAL);
1606 assert_return(!bus_pid_changed(bus), -ECHILD);
1608 r = bus_ensure_running(bus);
1612 *id = bus->server_id;
1616 static int bus_seal_message(sd_bus *b, sd_bus_message *m, usec_t timeout) {
1623 /* If we copy the same message to multiple
1624 * destinations, avoid using the same cookie
1626 b->cookie = MAX(b->cookie, BUS_MESSAGE_COOKIE(m));
1631 timeout = BUS_DEFAULT_TIMEOUT;
1633 if (!m->sender && b->patch_sender) {
1634 r = sd_bus_message_set_sender(m, b->patch_sender);
1639 return sd_bus_message_seal(m, ++b->cookie, timeout);
1642 static int bus_remarshal_message(sd_bus *b, sd_bus_message **m) {
1643 bool remarshal = false;
1647 /* wrong packet version */
1648 if (b->message_version != 0 && b->message_version != (*m)->header->version)
1651 /* wrong packet endianness */
1652 if (b->message_endian != 0 && b->message_endian != (*m)->header->endian)
1655 return remarshal ? bus_message_remarshal(b, m) : 0;
1658 int bus_seal_synthetic_message(sd_bus *b, sd_bus_message *m) {
1662 /* Fake some timestamps, if they were requested, and not
1663 * already initialized */
1664 if (b->attach_timestamp) {
1665 if (m->realtime <= 0)
1666 m->realtime = now(CLOCK_REALTIME);
1668 if (m->monotonic <= 0)
1669 m->monotonic = now(CLOCK_MONOTONIC);
1672 /* The bus specification says the serial number cannot be 0,
1673 * hence let's fill something in for synthetic messages. Since
1674 * synthetic messages might have a fake sender and we don't
1675 * want to interfere with the real sender's serial numbers we
1676 * pick a fixed, artificial one. We use (uint32_t) -1 rather
1677 * than (uint64_t) -1 since dbus1 only had 32bit identifiers,
1678 * even though kdbus can do 64bit. */
1679 return sd_bus_message_seal(m, 0xFFFFFFFFULL, 0);
1682 static int bus_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
1688 r = bus_socket_write_message(bus, m, idx);
1692 if (*idx >= BUS_MESSAGE_SIZE(m))
1693 log_debug("Sent message type=%s sender=%s destination=%s path=%s interface=%s member=%s cookie=%" PRIu64 " reply_cookie=%" PRIu64 " signature=%s error-name=%s error-message=%s",
1694 bus_message_type_to_string(m->header->type),
1695 strna(sd_bus_message_get_sender(m)),
1696 strna(sd_bus_message_get_destination(m)),
1697 strna(sd_bus_message_get_path(m)),
1698 strna(sd_bus_message_get_interface(m)),
1699 strna(sd_bus_message_get_member(m)),
1700 BUS_MESSAGE_COOKIE(m),
1702 strna(m->root_container.signature),
1703 strna(m->error.name),
1704 strna(m->error.message));
1709 static int dispatch_wqueue(sd_bus *bus) {
1713 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1715 while (bus->wqueue_size > 0) {
1717 r = bus_write_message(bus, bus->wqueue[0], &bus->windex);
1721 /* Didn't do anything this time */
1723 else if (bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
1724 /* Fully written. Let's drop the entry from
1727 * This isn't particularly optimized, but
1728 * well, this is supposed to be our worst-case
1729 * buffer only, and the socket buffer is
1730 * supposed to be our primary buffer, and if
1731 * it got full, then all bets are off
1735 sd_bus_message_unref(bus->wqueue[0]);
1736 memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
1746 static int bus_read_message(sd_bus *bus, bool hint_priority, int64_t priority) {
1749 return bus_socket_read_message(bus);
1752 int bus_rqueue_make_room(sd_bus *bus) {
1755 if (bus->rqueue_size >= BUS_RQUEUE_MAX)
1758 if (!GREEDY_REALLOC(bus->rqueue, bus->rqueue_allocated, bus->rqueue_size + 1))
1764 static int dispatch_rqueue(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **m) {
1769 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1771 /* Note that the priority logic is only available on kdbus,
1772 * where the rqueue is unused. We check the rqueue here
1773 * anyway, because it's simple... */
1776 if (bus->rqueue_size > 0) {
1777 /* Dispatch a queued message */
1779 *m = bus->rqueue[0];
1781 memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
1785 /* Try to read a new message */
1786 r = bus_read_message(bus, hint_priority, priority);
1796 _public_ int sd_bus_send(sd_bus *bus, sd_bus_message *_m, uint64_t *cookie) {
1797 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = sd_bus_message_ref(_m);
1800 assert_return(m, -EINVAL);
1805 assert_return(!bus_pid_changed(bus), -ECHILD);
1807 if (!BUS_IS_OPEN(bus->state))
1811 r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
1818 /* If the cookie number isn't kept, then we know that no reply
1820 if (!cookie && !m->sealed)
1821 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1823 r = bus_seal_message(bus, m, 0);
1827 /* Remarshall if we have to. This will possibly unref the
1828 * message and place a replacement in m */
1829 r = bus_remarshal_message(bus, &m);
1833 /* If this is a reply and no reply was requested, then let's
1834 * suppress this, if we can */
1838 if (IN_SET(bus->state, BUS_RUNNING, BUS_HELLO) && bus->wqueue_size <= 0) {
1841 r = bus_write_message(bus, m, &idx);
1843 if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
1844 bus_enter_closing(bus);
1851 if (idx < BUS_MESSAGE_SIZE(m)) {
1852 /* Wasn't fully written. So let's remember how
1853 * much was written. Note that the first entry
1854 * of the wqueue array is always allocated so
1855 * that we always can remember how much was
1857 bus->wqueue[0] = sd_bus_message_ref(m);
1858 bus->wqueue_size = 1;
1863 /* Just append it to the queue. */
1865 if (bus->wqueue_size >= BUS_WQUEUE_MAX)
1868 if (!GREEDY_REALLOC(bus->wqueue, bus->wqueue_allocated, bus->wqueue_size + 1))
1871 bus->wqueue[bus->wqueue_size++] = sd_bus_message_ref(m);
1876 *cookie = BUS_MESSAGE_COOKIE(m);
1881 _public_ int sd_bus_send_to(sd_bus *bus, sd_bus_message *m, const char *destination, uint64_t *cookie) {
1884 assert_return(m, -EINVAL);
1889 assert_return(!bus_pid_changed(bus), -ECHILD);
1891 if (!BUS_IS_OPEN(bus->state))
1894 if (!streq_ptr(m->destination, destination)) {
1899 r = sd_bus_message_set_destination(m, destination);
1904 return sd_bus_send(bus, m, cookie);
1907 static usec_t calc_elapse(sd_bus *bus, uint64_t usec) {
1910 if (usec == (uint64_t) -1)
1913 /* We start all timeouts the instant we enter BUS_HELLO/BUS_RUNNING state, so that the don't run in parallel
1914 * with any connection setup states. Hence, if a method callback is started earlier than that we just store the
1915 * relative timestamp, and afterwards the absolute one. */
1917 if (IN_SET(bus->state, BUS_WATCH_BIND, BUS_OPENING, BUS_AUTHENTICATING))
1920 return now(CLOCK_MONOTONIC) + usec;
1923 static int timeout_compare(const void *a, const void *b) {
1924 const struct reply_callback *x = a, *y = b;
1926 if (x->timeout_usec != 0 && y->timeout_usec == 0)
1929 if (x->timeout_usec == 0 && y->timeout_usec != 0)
1932 if (x->timeout_usec < y->timeout_usec)
1935 if (x->timeout_usec > y->timeout_usec)
1941 _public_ int sd_bus_call_async(
1945 sd_bus_message_handler_t callback,
1949 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = sd_bus_message_ref(_m);
1950 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *s = NULL;
1953 assert_return(m, -EINVAL);
1954 assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1955 assert_return(!m->sealed || (!!callback == !(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)), -EINVAL);
1960 assert_return(!bus_pid_changed(bus), -ECHILD);
1962 if (!BUS_IS_OPEN(bus->state))
1965 /* If no callback is specified and there's no interest in a slot, then there's no reason to ask for a reply */
1966 if (!callback && !slot && !m->sealed)
1967 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1969 r = ordered_hashmap_ensure_allocated(&bus->reply_callbacks, &uint64_hash_ops);
1973 r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
1977 r = bus_seal_message(bus, m, usec);
1981 r = bus_remarshal_message(bus, &m);
1985 if (slot || callback) {
1986 s = bus_slot_allocate(bus, !slot, BUS_REPLY_CALLBACK, sizeof(struct reply_callback), userdata);
1990 s->reply_callback.callback = callback;
1992 s->reply_callback.cookie = BUS_MESSAGE_COOKIE(m);
1993 r = ordered_hashmap_put(bus->reply_callbacks, &s->reply_callback.cookie, &s->reply_callback);
1995 s->reply_callback.cookie = 0;
1999 s->reply_callback.timeout_usec = calc_elapse(bus, m->timeout);
2000 if (s->reply_callback.timeout_usec != 0) {
2001 r = prioq_put(bus->reply_callbacks_prioq, &s->reply_callback, &s->reply_callback.prioq_idx);
2003 s->reply_callback.timeout_usec = 0;
2009 r = sd_bus_send(bus, m, s ? &s->reply_callback.cookie : NULL);
2020 int bus_ensure_running(sd_bus *bus) {
2025 if (IN_SET(bus->state, BUS_UNSET, BUS_CLOSED, BUS_CLOSING))
2027 if (bus->state == BUS_RUNNING)
2031 r = sd_bus_process(bus, NULL);
2034 if (bus->state == BUS_RUNNING)
2039 r = sd_bus_wait(bus, (uint64_t) -1);
2045 _public_ int sd_bus_call(
2049 sd_bus_error *error,
2050 sd_bus_message **reply) {
2052 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = sd_bus_message_ref(_m);
2058 bus_assert_return(m, -EINVAL, error);
2059 bus_assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL, error);
2060 bus_assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL, error);
2061 bus_assert_return(!bus_error_is_dirty(error), -EINVAL, error);
2066 bus_assert_return(!bus_pid_changed(bus), -ECHILD, error);
2068 if (!BUS_IS_OPEN(bus->state)) {
2073 r = bus_ensure_running(bus);
2077 i = bus->rqueue_size;
2079 r = bus_seal_message(bus, m, usec);
2083 r = bus_remarshal_message(bus, &m);
2087 r = sd_bus_send(bus, m, &cookie);
2091 timeout = calc_elapse(bus, m->timeout);
2096 while (i < bus->rqueue_size) {
2097 sd_bus_message *incoming = NULL;
2099 incoming = bus->rqueue[i];
2101 if (incoming->reply_cookie == cookie) {
2102 /* Found a match! */
2104 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
2106 log_debug_bus_message(incoming);
2108 if (incoming->header->type == SD_BUS_MESSAGE_METHOD_RETURN) {
2110 if (incoming->n_fds <= 0 || bus->accept_fd) {
2114 sd_bus_message_unref(incoming);
2119 r = sd_bus_error_setf(error, SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Reply message contained file descriptors which I couldn't accept. Sorry.");
2120 sd_bus_message_unref(incoming);
2123 } else if (incoming->header->type == SD_BUS_MESSAGE_METHOD_ERROR) {
2124 r = sd_bus_error_copy(error, &incoming->error);
2125 sd_bus_message_unref(incoming);
2132 } else if (BUS_MESSAGE_COOKIE(incoming) == cookie &&
2135 streq(bus->unique_name, incoming->sender)) {
2137 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
2140 /* Our own message? Somebody is trying
2141 * to send its own client a message,
2142 * let's not dead-lock, let's fail
2145 sd_bus_message_unref(incoming);
2150 /* Try to read more, right-away */
2154 r = bus_read_message(bus, false, 0);
2156 if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
2157 bus_enter_closing(bus);
2169 n = now(CLOCK_MONOTONIC);
2177 left = (uint64_t) -1;
2179 r = bus_poll(bus, true, left);
2187 r = dispatch_wqueue(bus);
2189 if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
2190 bus_enter_closing(bus);
2199 return sd_bus_error_set_errno(error, r);
2202 _public_ int sd_bus_get_fd(sd_bus *bus) {
2204 assert_return(bus, -EINVAL);
2205 assert_return(bus = bus_resolve(bus), -ENOPKG);
2206 assert_return(bus->input_fd == bus->output_fd, -EPERM);
2207 assert_return(!bus_pid_changed(bus), -ECHILD);
2209 if (bus->state == BUS_CLOSED)
2212 if (bus->inotify_fd >= 0)
2213 return bus->inotify_fd;
2215 if (bus->input_fd >= 0)
2216 return bus->input_fd;
2221 _public_ int sd_bus_get_events(sd_bus *bus) {
2224 assert_return(bus, -EINVAL);
2225 assert_return(bus = bus_resolve(bus), -ENOPKG);
2226 assert_return(!bus_pid_changed(bus), -ECHILD);
2228 switch (bus->state) {
2234 case BUS_WATCH_BIND:
2242 case BUS_AUTHENTICATING:
2243 if (bus_socket_auth_needs_write(bus))
2251 if (bus->rqueue_size <= 0)
2253 if (bus->wqueue_size > 0)
2261 assert_not_reached("Unknown state");
2267 _public_ int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
2268 struct reply_callback *c;
2270 assert_return(bus, -EINVAL);
2271 assert_return(bus = bus_resolve(bus), -ENOPKG);
2272 assert_return(timeout_usec, -EINVAL);
2273 assert_return(!bus_pid_changed(bus), -ECHILD);
2275 if (!BUS_IS_OPEN(bus->state) && bus->state != BUS_CLOSING)
2278 if (bus->track_queue) {
2283 switch (bus->state) {
2285 case BUS_AUTHENTICATING:
2286 *timeout_usec = bus->auth_timeout;
2291 if (bus->rqueue_size > 0) {
2296 c = prioq_peek(bus->reply_callbacks_prioq);
2298 *timeout_usec = (uint64_t) -1;
2302 if (c->timeout_usec == 0) {
2303 *timeout_usec = (uint64_t) -1;
2307 *timeout_usec = c->timeout_usec;
2314 case BUS_WATCH_BIND:
2316 *timeout_usec = (uint64_t) -1;
2320 assert_not_reached("Unknown or unexpected stat");
2324 static int process_timeout(sd_bus *bus) {
2325 _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2326 _cleanup_(sd_bus_message_unrefp) sd_bus_message* m = NULL;
2327 struct reply_callback *c;
2334 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
2336 c = prioq_peek(bus->reply_callbacks_prioq);
2340 n = now(CLOCK_MONOTONIC);
2341 if (c->timeout_usec > n)
2344 r = bus_message_new_synthetic_error(
2347 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
2352 r = bus_seal_synthetic_message(bus, m);
2356 assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
2357 c->timeout_usec = 0;
2359 ordered_hashmap_remove(bus->reply_callbacks, &c->cookie);
2362 slot = container_of(c, sd_bus_slot, reply_callback);
2364 bus->iteration_counter++;
2366 is_hello = bus->state == BUS_HELLO && c->callback == hello_callback;
2368 bus->current_message = m;
2369 bus->current_slot = sd_bus_slot_ref(slot);
2370 bus->current_handler = c->callback;
2371 bus->current_userdata = slot->userdata;
2372 r = c->callback(m, slot->userdata, &error_buffer);
2373 bus->current_userdata = NULL;
2374 bus->current_handler = NULL;
2375 bus->current_slot = NULL;
2376 bus->current_message = NULL;
2378 if (slot->floating) {
2379 bus_slot_disconnect(slot);
2380 sd_bus_slot_unref(slot);
2383 sd_bus_slot_unref(slot);
2385 /* When this is the hello message and it timed out, then make sure to propagate the error up, don't just log
2386 * and ignore the callback handler's return value. */
2390 return bus_maybe_reply_error(m, r, &error_buffer);
2393 static int process_hello(sd_bus *bus, sd_bus_message *m) {
2397 if (bus->state != BUS_HELLO)
2400 /* Let's make sure the first message on the bus is the HELLO
2401 * reply. But note that we don't actually parse the message
2402 * here (we leave that to the usual handling), we just verify
2403 * we don't let any earlier msg through. */
2405 if (!IN_SET(m->header->type, SD_BUS_MESSAGE_METHOD_RETURN, SD_BUS_MESSAGE_METHOD_ERROR))
2408 if (m->reply_cookie != 1)
2414 static int process_reply(sd_bus *bus, sd_bus_message *m) {
2415 _cleanup_(sd_bus_message_unrefp) sd_bus_message *synthetic_reply = NULL;
2416 _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2417 struct reply_callback *c;
2425 if (!IN_SET(m->header->type, SD_BUS_MESSAGE_METHOD_RETURN, SD_BUS_MESSAGE_METHOD_ERROR))
2428 if (m->destination && bus->unique_name && !streq_ptr(m->destination, bus->unique_name))
2431 c = ordered_hashmap_remove(bus->reply_callbacks, &m->reply_cookie);
2437 slot = container_of(c, sd_bus_slot, reply_callback);
2439 if (m->n_fds > 0 && !bus->accept_fd) {
2441 /* If the reply contained a file descriptor which we
2442 * didn't want we pass an error instead. */
2444 r = bus_message_new_synthetic_error(
2447 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Reply message contained file descriptor"),
2452 /* Copy over original timestamp */
2453 synthetic_reply->realtime = m->realtime;
2454 synthetic_reply->monotonic = m->monotonic;
2455 synthetic_reply->seqnum = m->seqnum;
2457 r = bus_seal_synthetic_message(bus, synthetic_reply);
2461 m = synthetic_reply;
2463 r = sd_bus_message_rewind(m, true);
2468 if (c->timeout_usec != 0) {
2469 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2470 c->timeout_usec = 0;
2473 is_hello = bus->state == BUS_HELLO && c->callback == hello_callback;
2475 bus->current_slot = sd_bus_slot_ref(slot);
2476 bus->current_handler = c->callback;
2477 bus->current_userdata = slot->userdata;
2478 r = c->callback(m, slot->userdata, &error_buffer);
2479 bus->current_userdata = NULL;
2480 bus->current_handler = NULL;
2481 bus->current_slot = NULL;
2483 if (slot->floating) {
2484 bus_slot_disconnect(slot);
2485 sd_bus_slot_unref(slot);
2488 sd_bus_slot_unref(slot);
2490 /* When this is the hello message and it failed, then make sure to propagate the error up, don't just log and
2491 * ignore the callback handler's return value. */
2495 return bus_maybe_reply_error(m, r, &error_buffer);
2498 static int process_filter(sd_bus *bus, sd_bus_message *m) {
2499 _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2500 struct filter_callback *l;
2507 bus->filter_callbacks_modified = false;
2509 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
2512 if (bus->filter_callbacks_modified)
2515 /* Don't run this more than once per iteration */
2516 if (l->last_iteration == bus->iteration_counter)
2519 l->last_iteration = bus->iteration_counter;
2521 r = sd_bus_message_rewind(m, true);
2525 slot = container_of(l, sd_bus_slot, filter_callback);
2527 bus->current_slot = sd_bus_slot_ref(slot);
2528 bus->current_handler = l->callback;
2529 bus->current_userdata = slot->userdata;
2530 r = l->callback(m, slot->userdata, &error_buffer);
2531 bus->current_userdata = NULL;
2532 bus->current_handler = NULL;
2533 bus->current_slot = sd_bus_slot_unref(slot);
2535 r = bus_maybe_reply_error(m, r, &error_buffer);
2541 } while (bus->filter_callbacks_modified);
2546 static int process_match(sd_bus *bus, sd_bus_message *m) {
2553 bus->match_callbacks_modified = false;
2555 r = bus_match_run(bus, &bus->match_callbacks, m);
2559 } while (bus->match_callbacks_modified);
2564 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
2565 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2571 if (bus->is_monitor)
2574 if (bus->manual_peer_interface)
2577 if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2580 if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2583 if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2586 if (streq_ptr(m->member, "Ping"))
2587 r = sd_bus_message_new_method_return(m, &reply);
2588 else if (streq_ptr(m->member, "GetMachineId")) {
2592 r = sd_id128_get_machine(&id);
2596 r = sd_bus_message_new_method_return(m, &reply);
2600 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2602 r = sd_bus_message_new_method_errorf(
2604 SD_BUS_ERROR_UNKNOWN_METHOD,
2605 "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2611 r = sd_bus_send(bus, reply, NULL);
2618 static int process_fd_check(sd_bus *bus, sd_bus_message *m) {
2622 /* If we got a message with a file descriptor which we didn't
2623 * want to accept, then let's drop it. How can this even
2624 * happen? For example, when the kernel queues a message into
2625 * an activatable names's queue which allows fds, and then is
2626 * delivered to us later even though we ourselves did not
2629 if (bus->is_monitor)
2638 if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2639 return 1; /* just eat it up */
2641 return sd_bus_reply_method_errorf(m, SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Message contains file descriptors, which I cannot accept. Sorry.");
2644 static int process_message(sd_bus *bus, sd_bus_message *m) {
2650 bus->current_message = m;
2651 bus->iteration_counter++;
2653 log_debug_bus_message(m);
2655 r = process_hello(bus, m);
2659 r = process_reply(bus, m);
2663 r = process_fd_check(bus, m);
2667 r = process_filter(bus, m);
2671 r = process_match(bus, m);
2675 r = process_builtin(bus, m);
2679 r = bus_process_object(bus, m);
2682 bus->current_message = NULL;
2686 static int dispatch_track(sd_bus *bus) {
2689 if (!bus->track_queue)
2692 bus_track_dispatch(bus->track_queue);
2696 static int process_running(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2697 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2701 assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
2703 r = process_timeout(bus);
2707 r = dispatch_wqueue(bus);
2711 r = dispatch_track(bus);
2715 r = dispatch_rqueue(bus, hint_priority, priority, &m);
2721 r = process_message(bus, m);
2726 r = sd_bus_message_rewind(m, true);
2735 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2737 log_debug("Unprocessed message call sender=%s object=%s interface=%s member=%s",
2738 strna(sd_bus_message_get_sender(m)),
2739 strna(sd_bus_message_get_path(m)),
2740 strna(sd_bus_message_get_interface(m)),
2741 strna(sd_bus_message_get_member(m)));
2743 r = sd_bus_reply_method_errorf(
2745 SD_BUS_ERROR_UNKNOWN_OBJECT,
2746 "Unknown object '%s'.", m->path);
2760 static int bus_exit_now(sd_bus *bus) {
2763 /* Exit due to close, if this is requested. If this is bus object is attached to an event source, invokes
2764 * sd_event_exit(), otherwise invokes libc exit(). */
2766 if (bus->exited) /* did we already exit? */
2768 if (!bus->exit_triggered) /* was the exit condition triggered? */
2770 if (!bus->exit_on_disconnect) /* Shall we actually exit on disconnection? */
2773 bus->exited = true; /* never exit more than once */
2775 log_debug("Bus connection disconnected, exiting.");
2778 return sd_event_exit(bus->event, EXIT_FAILURE);
2782 assert_not_reached("exit() didn't exit?");
2785 static int process_closing_reply_callback(sd_bus *bus, struct reply_callback *c) {
2786 _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2787 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2794 r = bus_message_new_synthetic_error(
2797 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2802 r = bus_seal_synthetic_message(bus, m);
2806 if (c->timeout_usec != 0) {
2807 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2808 c->timeout_usec = 0;
2811 ordered_hashmap_remove(bus->reply_callbacks, &c->cookie);
2814 slot = container_of(c, sd_bus_slot, reply_callback);
2816 bus->iteration_counter++;
2818 bus->current_message = m;
2819 bus->current_slot = sd_bus_slot_ref(slot);
2820 bus->current_handler = c->callback;
2821 bus->current_userdata = slot->userdata;
2822 r = c->callback(m, slot->userdata, &error_buffer);
2823 bus->current_userdata = NULL;
2824 bus->current_handler = NULL;
2825 bus->current_slot = NULL;
2826 bus->current_message = NULL;
2828 if (slot->floating) {
2829 bus_slot_disconnect(slot);
2830 sd_bus_slot_unref(slot);
2833 sd_bus_slot_unref(slot);
2835 return bus_maybe_reply_error(m, r, &error_buffer);
2838 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2839 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2840 struct reply_callback *c;
2844 assert(bus->state == BUS_CLOSING);
2846 /* First, fail all outstanding method calls */
2847 c = ordered_hashmap_first(bus->reply_callbacks);
2849 return process_closing_reply_callback(bus, c);
2851 /* Then, fake-drop all remaining bus tracking references */
2853 bus_track_close(bus->tracks);
2857 /* Then, synthesize a Disconnected message */
2858 r = sd_bus_message_new_signal(
2861 "/org/freedesktop/DBus/Local",
2862 "org.freedesktop.DBus.Local",
2867 bus_message_set_sender_local(bus, m);
2869 r = bus_seal_synthetic_message(bus, m);
2875 bus->current_message = m;
2876 bus->iteration_counter++;
2878 r = process_filter(bus, m);
2882 r = process_match(bus, m);
2886 /* Nothing else to do, exit now, if the condition holds */
2887 bus->exit_triggered = true;
2888 (void) bus_exit_now(bus);
2896 bus->current_message = NULL;
2901 static int bus_process_internal(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2902 BUS_DONT_DESTROY(bus);
2905 /* Returns 0 when we didn't do anything. This should cause the
2906 * caller to invoke sd_bus_wait() before returning the next
2907 * time. Returns > 0 when we did something, which possibly
2908 * means *ret is filled in with an unprocessed message. */
2910 assert_return(bus, -EINVAL);
2911 assert_return(bus = bus_resolve(bus), -ENOPKG);
2912 assert_return(!bus_pid_changed(bus), -ECHILD);
2914 /* We don't allow recursively invoking sd_bus_process(). */
2915 assert_return(!bus->current_message, -EBUSY);
2916 assert(!bus->current_slot);
2918 switch (bus->state) {
2926 case BUS_WATCH_BIND:
2927 r = bus_socket_process_watch_bind(bus);
2931 r = bus_socket_process_opening(bus);
2934 case BUS_AUTHENTICATING:
2935 r = bus_socket_process_authenticating(bus);
2940 r = process_running(bus, hint_priority, priority, ret);
2944 /* This branch initializes *ret, hence we don't use the generic error checking below */
2948 return process_closing(bus, ret);
2951 assert_not_reached("Unknown state");
2954 if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
2955 bus_enter_closing(bus);
2966 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2967 return bus_process_internal(bus, false, 0, ret);
2970 _public_ int sd_bus_process_priority(sd_bus *bus, int64_t priority, sd_bus_message **ret) {
2971 return bus_process_internal(bus, true, priority, ret);
2974 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2975 struct pollfd p[2] = {};
2978 usec_t m = USEC_INFINITY;
2982 if (bus->state == BUS_CLOSING)
2985 if (!BUS_IS_OPEN(bus->state))
2988 if (bus->state == BUS_WATCH_BIND) {
2989 assert(bus->inotify_fd >= 0);
2991 p[0].events = POLLIN;
2992 p[0].fd = bus->inotify_fd;
2997 e = sd_bus_get_events(bus);
3002 /* The caller really needs some more data, he doesn't
3003 * care about what's already read, or any timeouts
3004 * except its own. */
3008 /* The caller wants to process if there's something to
3009 * process, but doesn't care otherwise */
3011 r = sd_bus_get_timeout(bus, &until);
3015 m = usec_sub_unsigned(until, now(CLOCK_MONOTONIC));
3018 p[0].fd = bus->input_fd;
3019 if (bus->output_fd == bus->input_fd) {
3023 p[0].events = e & POLLIN;
3024 p[1].fd = bus->output_fd;
3025 p[1].events = e & POLLOUT;
3030 if (timeout_usec != (uint64_t) -1 && (m == USEC_INFINITY || timeout_usec < m))
3033 r = ppoll(p, n, m == USEC_INFINITY ? NULL : timespec_store(&ts, m), NULL);
3037 return r > 0 ? 1 : 0;
3040 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
3042 assert_return(bus, -EINVAL);
3043 assert_return(bus = bus_resolve(bus), -ENOPKG);
3044 assert_return(!bus_pid_changed(bus), -ECHILD);
3046 if (bus->state == BUS_CLOSING)
3049 if (!BUS_IS_OPEN(bus->state))
3052 if (bus->rqueue_size > 0)
3055 return bus_poll(bus, false, timeout_usec);
3058 _public_ int sd_bus_flush(sd_bus *bus) {
3061 assert_return(bus, -EINVAL);
3062 assert_return(bus = bus_resolve(bus), -ENOPKG);
3063 assert_return(!bus_pid_changed(bus), -ECHILD);
3065 if (bus->state == BUS_CLOSING)
3068 if (!BUS_IS_OPEN(bus->state))
3071 /* We never were connected? Don't hang in inotify for good, as there's no timeout set for it */
3072 if (bus->state == BUS_WATCH_BIND)
3075 r = bus_ensure_running(bus);
3079 if (bus->wqueue_size <= 0)
3083 r = dispatch_wqueue(bus);
3085 if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
3086 bus_enter_closing(bus);
3093 if (bus->wqueue_size <= 0)
3096 r = bus_poll(bus, false, (uint64_t) -1);
3102 _public_ int sd_bus_add_filter(
3105 sd_bus_message_handler_t callback,
3110 assert_return(bus, -EINVAL);
3111 assert_return(bus = bus_resolve(bus), -ENOPKG);
3112 assert_return(callback, -EINVAL);
3113 assert_return(!bus_pid_changed(bus), -ECHILD);
3115 s = bus_slot_allocate(bus, !slot, BUS_FILTER_CALLBACK, sizeof(struct filter_callback), userdata);
3119 s->filter_callback.callback = callback;
3121 bus->filter_callbacks_modified = true;
3122 LIST_PREPEND(callbacks, bus->filter_callbacks, &s->filter_callback);
3130 static int add_match_callback(
3133 sd_bus_error *ret_error) {
3135 sd_bus_slot *match_slot = userdata;
3136 bool failed = false;
3142 sd_bus_slot_ref(match_slot);
3144 if (sd_bus_message_is_method_error(m, NULL)) {
3145 log_debug_errno(sd_bus_message_get_errno(m),
3146 "Unable to add match %s, failing connection: %s",
3147 match_slot->match_callback.match_string,
3148 sd_bus_message_get_error(m)->message);
3152 log_debug("Match %s successfully installed.", match_slot->match_callback.match_string);
3154 if (match_slot->match_callback.install_callback) {
3157 bus = sd_bus_message_get_bus(m);
3159 /* This function has been called as slot handler, and we want to call another slot handler. Let's
3160 * update the slot callback metadata temporarily with our own data, and then revert back to the old
3163 assert(bus->current_slot == match_slot->match_callback.install_slot);
3164 assert(bus->current_handler == add_match_callback);
3165 assert(bus->current_userdata == userdata);
3167 bus->current_slot = match_slot;
3168 bus->current_handler = match_slot->match_callback.install_callback;
3169 bus->current_userdata = match_slot->userdata;
3171 r = match_slot->match_callback.install_callback(m, match_slot->userdata, ret_error);
3173 bus->current_slot = match_slot->match_callback.install_slot;
3174 bus->current_handler = add_match_callback;
3175 bus->current_userdata = userdata;
3177 match_slot->match_callback.install_slot = sd_bus_slot_unref(match_slot->match_callback.install_slot);
3179 if (failed) /* Generic failure handling: destroy the connection */
3180 bus_enter_closing(sd_bus_message_get_bus(m));
3185 if (failed && match_slot->floating) {
3186 bus_slot_disconnect(match_slot);
3187 sd_bus_slot_unref(match_slot);
3190 sd_bus_slot_unref(match_slot);
3195 static int bus_add_match_full(
3200 sd_bus_message_handler_t callback,
3201 sd_bus_message_handler_t install_callback,
3204 struct bus_match_component *components = NULL;
3205 unsigned n_components = 0;
3206 sd_bus_slot *s = NULL;
3209 assert_return(bus, -EINVAL);
3210 assert_return(bus = bus_resolve(bus), -ENOPKG);
3211 assert_return(match, -EINVAL);
3212 assert_return(!bus_pid_changed(bus), -ECHILD);
3214 r = bus_match_parse(match, &components, &n_components);
3218 s = bus_slot_allocate(bus, !slot, BUS_MATCH_CALLBACK, sizeof(struct match_callback), userdata);
3224 s->match_callback.callback = callback;
3225 s->match_callback.install_callback = install_callback;
3227 if (bus->bus_client) {
3228 enum bus_match_scope scope;
3230 scope = bus_match_get_scope(components, n_components);
3232 /* Do not install server-side matches for matches against the local service, interface or bus path. */
3233 if (scope != BUS_MATCH_LOCAL) {
3235 /* We store the original match string, so that we can use it to remove the match again. */
3237 s->match_callback.match_string = strdup(match);
3238 if (!s->match_callback.match_string) {
3244 r = bus_add_match_internal_async(bus,
3245 &s->match_callback.install_slot,
3246 s->match_callback.match_string,
3253 /* Make the slot of the match call floating now. We need the reference, but we don't
3254 * want that this match pins the bus object, hence we first create it non-floating, but
3255 * then make it floating. */
3256 r = sd_bus_slot_set_floating(s->match_callback.install_slot, true);
3258 r = bus_add_match_internal(bus, s->match_callback.match_string);
3262 s->match_added = true;
3266 bus->match_callbacks_modified = true;
3267 r = bus_match_add(&bus->match_callbacks, components, n_components, &s->match_callback);
3276 bus_match_parse_free(components, n_components);
3277 sd_bus_slot_unref(s);
3282 #if 0 /// UNNEEDED by elogind
3284 _public_ int sd_bus_add_match(
3288 sd_bus_message_handler_t callback,
3291 return bus_add_match_full(bus, slot, false, match, callback, NULL, userdata);
3294 _public_ int sd_bus_add_match_async(
3298 sd_bus_message_handler_t callback,
3299 sd_bus_message_handler_t install_callback,
3302 return bus_add_match_full(bus, slot, true, match, callback, install_callback, userdata);
3305 bool bus_pid_changed(sd_bus *bus) {
3308 /* We don't support people creating a bus connection and
3309 * keeping it around over a fork(). Let's complain. */
3311 return bus->original_pid != getpid_cached();
3314 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
3315 sd_bus *bus = userdata;
3320 /* Note that this is called both on input_fd, output_fd as well as inotify_fd events */
3322 r = sd_bus_process(bus, NULL);
3324 log_debug_errno(r, "Processing of bus failed, closing down: %m");
3325 bus_enter_closing(bus);
3331 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
3332 sd_bus *bus = userdata;
3337 r = sd_bus_process(bus, NULL);
3339 log_debug_errno(r, "Processing of bus failed, closing down: %m");
3340 bus_enter_closing(bus);
3346 static int prepare_callback(sd_event_source *s, void *userdata) {
3347 sd_bus *bus = userdata;
3354 e = sd_bus_get_events(bus);
3360 if (bus->output_fd != bus->input_fd) {
3362 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
3366 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
3368 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
3372 r = sd_bus_get_timeout(bus, &until);
3378 j = sd_event_source_set_time(bus->time_event_source, until);
3385 r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
3392 log_debug_errno(r, "Preparing of bus events failed, closing down: %m");
3393 bus_enter_closing(bus);
3398 static int quit_callback(sd_event_source *event, void *userdata) {
3399 sd_bus *bus = userdata;
3409 int bus_attach_io_events(sd_bus *bus) {
3414 if (bus->input_fd < 0)
3420 if (!bus->input_io_event_source) {
3421 r = sd_event_add_io(bus->event, &bus->input_io_event_source, bus->input_fd, 0, io_callback, bus);
3425 r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
3429 r = sd_event_source_set_priority(bus->input_io_event_source, bus->event_priority);
3433 r = sd_event_source_set_description(bus->input_io_event_source, "bus-input");
3435 r = sd_event_source_set_io_fd(bus->input_io_event_source, bus->input_fd);
3440 if (bus->output_fd != bus->input_fd) {
3441 assert(bus->output_fd >= 0);
3443 if (!bus->output_io_event_source) {
3444 r = sd_event_add_io(bus->event, &bus->output_io_event_source, bus->output_fd, 0, io_callback, bus);
3448 r = sd_event_source_set_priority(bus->output_io_event_source, bus->event_priority);
3452 r = sd_event_source_set_description(bus->input_io_event_source, "bus-output");
3454 r = sd_event_source_set_io_fd(bus->output_io_event_source, bus->output_fd);
3463 static void bus_detach_io_events(sd_bus *bus) {
3466 if (bus->input_io_event_source) {
3467 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
3468 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
3471 if (bus->output_io_event_source) {
3472 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
3473 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
3477 int bus_attach_inotify_event(sd_bus *bus) {
3482 if (bus->inotify_fd < 0)
3488 if (!bus->inotify_event_source) {
3489 r = sd_event_add_io(bus->event, &bus->inotify_event_source, bus->inotify_fd, EPOLLIN, io_callback, bus);
3493 r = sd_event_source_set_priority(bus->inotify_event_source, bus->event_priority);
3497 r = sd_event_source_set_description(bus->inotify_event_source, "bus-inotify");
3499 r = sd_event_source_set_io_fd(bus->inotify_event_source, bus->inotify_fd);
3506 static void bus_detach_inotify_event(sd_bus *bus) {
3509 if (bus->inotify_event_source) {
3510 sd_event_source_set_enabled(bus->inotify_event_source, SD_EVENT_OFF);
3511 bus->inotify_event_source = sd_event_source_unref(bus->inotify_event_source);
3515 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
3518 assert_return(bus, -EINVAL);
3519 assert_return(bus = bus_resolve(bus), -ENOPKG);
3520 assert_return(!bus->event, -EBUSY);
3522 assert(!bus->input_io_event_source);
3523 assert(!bus->output_io_event_source);
3524 assert(!bus->time_event_source);
3527 bus->event = sd_event_ref(event);
3529 r = sd_event_default(&bus->event);
3534 bus->event_priority = priority;
3536 r = sd_event_add_time(bus->event, &bus->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, bus);
3540 r = sd_event_source_set_priority(bus->time_event_source, priority);
3544 r = sd_event_source_set_description(bus->time_event_source, "bus-time");
3548 r = sd_event_add_exit(bus->event, &bus->quit_event_source, quit_callback, bus);
3552 r = sd_event_source_set_description(bus->quit_event_source, "bus-exit");
3556 r = bus_attach_io_events(bus);
3560 r = bus_attach_inotify_event(bus);
3567 sd_bus_detach_event(bus);
3571 _public_ int sd_bus_detach_event(sd_bus *bus) {
3572 assert_return(bus, -EINVAL);
3573 assert_return(bus = bus_resolve(bus), -ENOPKG);
3578 bus_detach_io_events(bus);
3579 bus_detach_inotify_event(bus);
3581 if (bus->time_event_source) {
3582 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
3583 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
3586 if (bus->quit_event_source) {
3587 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
3588 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
3591 bus->event = sd_event_unref(bus->event);
3595 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
3596 assert_return(bus, NULL);
3601 _public_ sd_bus_message* sd_bus_get_current_message(sd_bus *bus) {
3602 assert_return(bus, NULL);
3604 return bus->current_message;
3607 _public_ sd_bus_slot* sd_bus_get_current_slot(sd_bus *bus) {
3608 assert_return(bus, NULL);
3610 return bus->current_slot;
3613 _public_ sd_bus_message_handler_t sd_bus_get_current_handler(sd_bus *bus) {
3614 assert_return(bus, NULL);
3616 return bus->current_handler;
3619 _public_ void* sd_bus_get_current_userdata(sd_bus *bus) {
3620 assert_return(bus, NULL);
3622 return bus->current_userdata;
3625 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
3630 assert(default_bus);
3633 return !!*default_bus;
3636 *ret = sd_bus_ref(*default_bus);
3644 b->default_bus_ptr = default_bus;
3652 _public_ int sd_bus_default_system(sd_bus **ret) {
3653 return bus_default(sd_bus_open_system, &default_system_bus, ret);
3656 _public_ int sd_bus_default_user(sd_bus **ret) {
3657 #if 0 /// elogind does not support user buses
3658 return bus_default(sd_bus_open_user, &default_user_bus, ret);
3660 return sd_bus_default_system(ret);
3664 _public_ int sd_bus_default(sd_bus **ret) {
3665 int (*bus_open)(sd_bus **) = NULL;
3668 busp = bus_choose_default(&bus_open);
3669 return bus_default(bus_open, busp, ret);
3672 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
3673 assert_return(b, -EINVAL);
3674 assert_return(tid, -EINVAL);
3675 assert_return(!bus_pid_changed(b), -ECHILD);
3683 return sd_event_get_tid(b->event, tid);
3688 _public_ int sd_bus_path_encode(const char *prefix, const char *external_id, char **ret_path) {
3689 _cleanup_free_ char *e = NULL;
3692 assert_return(object_path_is_valid(prefix), -EINVAL);
3693 assert_return(external_id, -EINVAL);
3694 assert_return(ret_path, -EINVAL);
3696 e = bus_label_escape(external_id);
3700 ret = strjoin(prefix, "/", e);
3708 _public_ int sd_bus_path_decode(const char *path, const char *prefix, char **external_id) {
3712 assert_return(object_path_is_valid(path), -EINVAL);
3713 assert_return(object_path_is_valid(prefix), -EINVAL);
3714 assert_return(external_id, -EINVAL);
3716 e = object_path_startswith(path, prefix);
3718 *external_id = NULL;
3722 ret = bus_label_unescape(e);
3730 _public_ int sd_bus_path_encode_many(char **out, const char *path_template, ...) {
3731 _cleanup_strv_free_ char **labels = NULL;
3732 char *path, *path_pos, **label_pos;
3733 const char *sep, *template_pos;
3738 assert_return(out, -EINVAL);
3739 assert_return(path_template, -EINVAL);
3741 path_length = strlen(path_template);
3743 va_start(list, path_template);
3744 for (sep = strchr(path_template, '%'); sep; sep = strchr(sep + 1, '%')) {
3748 arg = va_arg(list, const char *);
3754 label = bus_label_escape(arg);
3760 r = strv_consume(&labels, label);
3766 /* add label length, but account for the format character */
3767 path_length += strlen(label) - 1;
3771 path = malloc(path_length + 1);
3778 for (template_pos = path_template; *template_pos; ) {
3779 sep = strchrnul(template_pos, '%');
3780 path_pos = mempcpy(path_pos, template_pos, sep - template_pos);
3784 path_pos = stpcpy(path_pos, *label_pos++);
3785 template_pos = sep + 1;
3793 _public_ int sd_bus_path_decode_many(const char *path, const char *path_template, ...) {
3794 _cleanup_strv_free_ char **labels = NULL;
3795 const char *template_pos, *path_pos;
3801 * This decodes an object-path based on a template argument. The
3802 * template consists of a verbatim path, optionally including special
3805 * - Each occurrence of '%' in the template matches an arbitrary
3806 * substring of a label in the given path. At most one such
3807 * directive is allowed per label. For each such directive, the
3808 * caller must provide an output parameter (char **) via va_arg. If
3809 * NULL is passed, the given label is verified, but not returned.
3810 * For each matched label, the *decoded* label is stored in the
3811 * passed output argument, and the caller is responsible to free
3812 * it. Note that the output arguments are only modified if the
3813 * actualy path matched the template. Otherwise, they're left
3816 * This function returns <0 on error, 0 if the path does not match the
3817 * template, 1 if it matched.
3820 assert_return(path, -EINVAL);
3821 assert_return(path_template, -EINVAL);
3825 for (template_pos = path_template; *template_pos; ) {
3830 /* verify everything until the next '%' matches verbatim */
3831 sep = strchrnul(template_pos, '%');
3832 length = sep - template_pos;
3833 if (strncmp(path_pos, template_pos, length))
3837 template_pos += length;
3842 /* We found the next '%' character. Everything up until here
3843 * matched. We now skip ahead to the end of this label and make
3844 * sure it matches the tail of the label in the path. Then we
3845 * decode the string in-between and save it for later use. */
3847 ++template_pos; /* skip over '%' */
3849 sep = strchrnul(template_pos, '/');
3850 length = sep - template_pos; /* length of suffix to match verbatim */
3852 /* verify the suffixes match */
3853 sep = strchrnul(path_pos, '/');
3854 if (sep - path_pos < (ssize_t)length ||
3855 strncmp(sep - length, template_pos, length))
3858 template_pos += length; /* skip over matched label */
3859 length = sep - path_pos - length; /* length of sub-label to decode */
3861 /* store unescaped label for later use */
3862 label = bus_label_unescape_n(path_pos, length);
3866 r = strv_consume(&labels, label);
3870 path_pos = sep; /* skip decoded label and suffix */
3873 /* end of template must match end of path */
3877 /* copy the labels over to the caller */
3878 va_start(list, path_template);
3879 for (label_pos = labels; label_pos && *label_pos; ++label_pos) {
3882 arg = va_arg(list, char **);
3890 labels = mfree(labels);
3894 _public_ int sd_bus_try_close(sd_bus *bus) {
3895 assert_return(bus, -EINVAL);
3896 assert_return(bus = bus_resolve(bus), -ENOPKG);
3897 assert_return(!bus_pid_changed(bus), -ECHILD);
3902 _public_ int sd_bus_get_description(sd_bus *bus, const char **description) {
3903 assert_return(bus, -EINVAL);
3904 assert_return(bus = bus_resolve(bus), -ENOPKG);
3905 assert_return(description, -EINVAL);
3906 assert_return(bus->description, -ENXIO);
3907 assert_return(!bus_pid_changed(bus), -ECHILD);
3909 if (bus->description)
3910 *description = bus->description;
3911 else if (bus->is_system)
3912 *description = "system";
3913 else if (bus->is_user)
3914 *description = "user";
3916 *description = NULL;
3921 int bus_get_root_path(sd_bus *bus) {
3924 if (bus->cgroup_root)
3927 r = cg_get_root_path(&bus->cgroup_root);
3929 bus->cgroup_root = strdup("/");
3930 if (!bus->cgroup_root)
3939 _public_ int sd_bus_get_scope(sd_bus *bus, const char **scope) {
3940 assert_return(bus, -EINVAL);
3941 assert_return(bus = bus_resolve(bus), -ENOPKG);
3942 assert_return(scope, -EINVAL);
3943 assert_return(!bus_pid_changed(bus), -ECHILD);
3950 if (bus->is_system) {
3958 _public_ int sd_bus_get_address(sd_bus *bus, const char **address) {
3960 assert_return(bus, -EINVAL);
3961 assert_return(bus = bus_resolve(bus), -ENOPKG);
3962 assert_return(address, -EINVAL);
3963 assert_return(!bus_pid_changed(bus), -ECHILD);
3966 *address = bus->address;
3973 _public_ int sd_bus_get_creds_mask(sd_bus *bus, uint64_t *mask) {
3974 assert_return(bus, -EINVAL);
3975 assert_return(bus = bus_resolve(bus), -ENOPKG);
3976 assert_return(mask, -EINVAL);
3977 assert_return(!bus_pid_changed(bus), -ECHILD);
3979 *mask = bus->creds_mask;
3983 _public_ int sd_bus_is_bus_client(sd_bus *bus) {
3984 assert_return(bus, -EINVAL);
3985 assert_return(bus = bus_resolve(bus), -ENOPKG);
3986 assert_return(!bus_pid_changed(bus), -ECHILD);
3988 return bus->bus_client;
3991 _public_ int sd_bus_is_server(sd_bus *bus) {
3992 assert_return(bus, -EINVAL);
3993 assert_return(bus = bus_resolve(bus), -ENOPKG);
3994 assert_return(!bus_pid_changed(bus), -ECHILD);
3996 return bus->is_server;
3999 _public_ int sd_bus_is_anonymous(sd_bus *bus) {
4000 assert_return(bus, -EINVAL);
4001 assert_return(bus = bus_resolve(bus), -ENOPKG);
4002 assert_return(!bus_pid_changed(bus), -ECHILD);
4004 return bus->anonymous_auth;
4007 _public_ int sd_bus_is_trusted(sd_bus *bus) {
4008 assert_return(bus, -EINVAL);
4009 assert_return(bus = bus_resolve(bus), -ENOPKG);
4010 assert_return(!bus_pid_changed(bus), -ECHILD);
4012 return bus->trusted;
4015 _public_ int sd_bus_is_monitor(sd_bus *bus) {
4016 assert_return(bus, -EINVAL);
4017 assert_return(bus = bus_resolve(bus), -ENOPKG);
4018 assert_return(!bus_pid_changed(bus), -ECHILD);
4020 return bus->is_monitor;
4023 static void flush_close(sd_bus *bus) {
4027 /* Flushes and closes the specified bus. We take a ref before,
4028 * to ensure the flushing does not cause the bus to be
4031 sd_bus_flush_close_unref(sd_bus_ref(bus));
4034 _public_ void sd_bus_default_flush_close(void) {
4035 flush_close(default_starter_bus);
4036 #if 0 /// elogind does not support user buses
4037 flush_close(default_user_bus);
4039 flush_close(default_system_bus);
4042 _public_ int sd_bus_set_exit_on_disconnect(sd_bus *bus, int b) {
4043 assert_return(bus, -EINVAL);
4044 assert_return(bus = bus_resolve(bus), -ENOPKG);
4046 /* Turns on exit-on-disconnect, and triggers it immediately if the bus connection was already
4047 * disconnected. Note that this is triggered exclusively on disconnections triggered by the server side, never
4048 * from the client side. */
4049 bus->exit_on_disconnect = b;
4051 /* If the exit condition was triggered already, exit immediately. */
4052 return bus_exit_now(bus);
4055 _public_ int sd_bus_get_exit_on_disconnect(sd_bus *bus) {
4056 assert_return(bus, -EINVAL);
4057 assert_return(bus = bus_resolve(bus), -ENOPKG);
4059 return bus->exit_on_disconnect;
4062 _public_ int sd_bus_set_sender(sd_bus *bus, const char *sender) {
4063 assert_return(bus, -EINVAL);
4064 assert_return(bus = bus_resolve(bus), -ENOPKG);
4065 assert_return(!bus->bus_client, -EPERM);
4066 assert_return(!sender || service_name_is_valid(sender), -EINVAL);
4068 return free_and_strdup(&bus->patch_sender, sender);
4071 _public_ int sd_bus_get_sender(sd_bus *bus, const char **ret) {
4072 assert_return(bus, -EINVAL);
4073 assert_return(bus = bus_resolve(bus), -ENOPKG);
4074 assert_return(ret, -EINVAL);
4076 if (!bus->patch_sender)
4079 *ret = bus->patch_sender;
4083 _public_ int sd_bus_get_n_queued_read(sd_bus *bus, uint64_t *ret) {
4084 assert_return(bus, -EINVAL);
4085 assert_return(bus = bus_resolve(bus), -ENOPKG);
4086 assert_return(!bus_pid_changed(bus), -ECHILD);
4087 assert_return(ret, -EINVAL);
4089 *ret = bus->rqueue_size;
4093 _public_ int sd_bus_get_n_queued_write(sd_bus *bus, uint64_t *ret) {
4094 assert_return(bus, -EINVAL);
4095 assert_return(bus = bus_resolve(bus), -ENOPKG);
4096 assert_return(!bus_pid_changed(bus), -ECHILD);
4097 assert_return(ret, -EINVAL);
4099 *ret = bus->wqueue_size;