1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2013 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
32 #include "alloc-util.h"
33 #include "bus-container.h"
34 #include "bus-control.h"
35 #include "bus-internal.h"
36 #include "bus-kernel.h"
37 #include "bus-label.h"
38 #include "bus-message.h"
39 #include "bus-objects.h"
40 #include "bus-protocol.h"
42 #include "bus-socket.h"
43 #include "bus-track.h"
46 #include "cgroup-util.h"
49 #include "hexdecoct.h"
50 #include "hostname-util.h"
53 #include "parse-util.h"
54 #include "string-util.h"
58 #define log_debug_bus_message(m) \
60 sd_bus_message *_mm = (m); \
61 log_debug("Got message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%" PRIu64 " reply_cookie=%" PRIu64 " error=%s", \
62 bus_message_type_to_string(_mm->header->type), \
63 strna(sd_bus_message_get_sender(_mm)), \
64 strna(sd_bus_message_get_destination(_mm)), \
65 strna(sd_bus_message_get_path(_mm)), \
66 strna(sd_bus_message_get_interface(_mm)), \
67 strna(sd_bus_message_get_member(_mm)), \
68 BUS_MESSAGE_COOKIE(_mm), \
70 strna(_mm->error.message)); \
73 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec);
74 static int attach_io_events(sd_bus *b);
75 static void detach_io_events(sd_bus *b);
77 static thread_local sd_bus *default_system_bus = NULL;
78 /// UNNEEDED by elogind
80 static thread_local sd_bus *default_user_bus = NULL;
82 static thread_local sd_bus *default_starter_bus = NULL;
84 static void bus_close_fds(sd_bus *b) {
89 if (b->input_fd != b->output_fd)
90 safe_close(b->output_fd);
91 b->output_fd = b->input_fd = safe_close(b->input_fd);
94 static void bus_reset_queues(sd_bus *b) {
97 while (b->rqueue_size > 0)
98 sd_bus_message_unref(b->rqueue[--b->rqueue_size]);
100 b->rqueue = mfree(b->rqueue);
101 b->rqueue_allocated = 0;
103 while (b->wqueue_size > 0)
104 sd_bus_message_unref(b->wqueue[--b->wqueue_size]);
106 b->wqueue = mfree(b->wqueue);
107 b->wqueue_allocated = 0;
110 static void bus_free(sd_bus *b) {
114 assert(!b->track_queue);
116 b->state = BUS_CLOSED;
118 sd_bus_detach_event(b);
120 while ((s = b->slots)) {
121 /* At this point only floating slots can still be
122 * around, because the non-floating ones keep a
123 * reference to the bus, and we thus couldn't be
124 * destructing right now... We forcibly disconnect the
125 * slots here, so that they still can be referenced by
126 * apps, but are dead. */
129 bus_slot_disconnect(s);
130 sd_bus_slot_unref(s);
133 if (b->default_bus_ptr)
134 *b->default_bus_ptr = NULL;
139 munmap(b->kdbus_buffer, KDBUS_POOL_SIZE);
143 free(b->unique_name);
144 free(b->auth_buffer);
149 free(b->cgroup_root);
150 free(b->description);
153 strv_free(b->exec_argv);
155 close_many(b->fds, b->n_fds);
160 ordered_hashmap_free_free(b->reply_callbacks);
161 prioq_free(b->reply_callbacks_prioq);
163 assert(b->match_callbacks.type == BUS_MATCH_ROOT);
164 bus_match_free(&b->match_callbacks);
166 hashmap_free_free(b->vtable_methods);
167 hashmap_free_free(b->vtable_properties);
169 assert(hashmap_isempty(b->nodes));
170 hashmap_free(b->nodes);
172 bus_kernel_flush_memfd(b);
174 assert_se(pthread_mutex_destroy(&b->memfd_cache_mutex) == 0);
179 _public_ int sd_bus_new(sd_bus **ret) {
182 assert_return(ret, -EINVAL);
188 r->n_ref = REFCNT_INIT;
189 r->input_fd = r->output_fd = -1;
190 r->message_version = 1;
191 r->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
192 r->hello_flags |= KDBUS_HELLO_ACCEPT_FD;
193 r->attach_flags |= KDBUS_ATTACH_NAMES;
194 r->original_pid = getpid();
196 assert_se(pthread_mutex_init(&r->memfd_cache_mutex, NULL) == 0);
198 /* We guarantee that wqueue always has space for at least one
200 if (!GREEDY_REALLOC(r->wqueue, r->wqueue_allocated, 1)) {
209 _public_ int sd_bus_set_address(sd_bus *bus, const char *address) {
212 assert_return(bus, -EINVAL);
213 assert_return(bus->state == BUS_UNSET, -EPERM);
214 assert_return(address, -EINVAL);
215 assert_return(!bus_pid_changed(bus), -ECHILD);
227 _public_ int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd) {
228 assert_return(bus, -EINVAL);
229 assert_return(bus->state == BUS_UNSET, -EPERM);
230 assert_return(input_fd >= 0, -EBADF);
231 assert_return(output_fd >= 0, -EBADF);
232 assert_return(!bus_pid_changed(bus), -ECHILD);
234 bus->input_fd = input_fd;
235 bus->output_fd = output_fd;
239 /// UNNEEDED by elogind
241 _public_ int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]) {
244 assert_return(bus, -EINVAL);
245 assert_return(bus->state == BUS_UNSET, -EPERM);
246 assert_return(path, -EINVAL);
247 assert_return(!strv_isempty(argv), -EINVAL);
248 assert_return(!bus_pid_changed(bus), -ECHILD);
260 free(bus->exec_path);
261 strv_free(bus->exec_argv);
269 _public_ int sd_bus_set_bus_client(sd_bus *bus, int b) {
270 assert_return(bus, -EINVAL);
271 assert_return(bus->state == BUS_UNSET, -EPERM);
272 assert_return(!bus_pid_changed(bus), -ECHILD);
274 bus->bus_client = !!b;
278 _public_ int sd_bus_set_monitor(sd_bus *bus, int b) {
279 assert_return(bus, -EINVAL);
280 assert_return(bus->state == BUS_UNSET, -EPERM);
281 assert_return(!bus_pid_changed(bus), -ECHILD);
283 SET_FLAG(bus->hello_flags, KDBUS_HELLO_MONITOR, b);
287 _public_ int sd_bus_negotiate_fds(sd_bus *bus, int b) {
288 assert_return(bus, -EINVAL);
289 assert_return(bus->state == BUS_UNSET, -EPERM);
290 assert_return(!bus_pid_changed(bus), -ECHILD);
292 SET_FLAG(bus->hello_flags, KDBUS_HELLO_ACCEPT_FD, b);
296 _public_ int sd_bus_negotiate_timestamp(sd_bus *bus, int b) {
298 assert_return(bus, -EINVAL);
299 assert_return(!IN_SET(bus->state, BUS_CLOSING, BUS_CLOSED), -EPERM);
300 assert_return(!bus_pid_changed(bus), -ECHILD);
302 new_flags = bus->attach_flags;
303 SET_FLAG(new_flags, KDBUS_ATTACH_TIMESTAMP, b);
305 if (bus->attach_flags == new_flags)
308 bus->attach_flags = new_flags;
309 if (bus->state != BUS_UNSET && bus->is_kernel)
310 bus_kernel_realize_attach_flags(bus);
315 _public_ int sd_bus_negotiate_creds(sd_bus *bus, int b, uint64_t mask) {
318 assert_return(bus, -EINVAL);
319 assert_return(mask <= _SD_BUS_CREDS_ALL, -EINVAL);
320 assert_return(!IN_SET(bus->state, BUS_CLOSING, BUS_CLOSED), -EPERM);
321 assert_return(!bus_pid_changed(bus), -ECHILD);
324 bus->creds_mask |= mask;
326 bus->creds_mask &= ~mask;
328 /* The well knowns we need unconditionally, so that matches can work */
329 bus->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
331 /* Make sure we don't lose the timestamp flag */
332 new_flags = (bus->attach_flags & KDBUS_ATTACH_TIMESTAMP) | attach_flags_to_kdbus(bus->creds_mask);
333 if (bus->attach_flags == new_flags)
336 bus->attach_flags = new_flags;
337 if (bus->state != BUS_UNSET && bus->is_kernel)
338 bus_kernel_realize_attach_flags(bus);
343 _public_ int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id) {
344 assert_return(bus, -EINVAL);
345 assert_return(b || sd_id128_equal(server_id, SD_ID128_NULL), -EINVAL);
346 assert_return(bus->state == BUS_UNSET, -EPERM);
347 assert_return(!bus_pid_changed(bus), -ECHILD);
349 bus->is_server = !!b;
350 bus->server_id = server_id;
354 _public_ int sd_bus_set_anonymous(sd_bus *bus, int b) {
355 assert_return(bus, -EINVAL);
356 assert_return(bus->state == BUS_UNSET, -EPERM);
357 assert_return(!bus_pid_changed(bus), -ECHILD);
359 bus->anonymous_auth = !!b;
363 _public_ int sd_bus_set_trusted(sd_bus *bus, int b) {
364 assert_return(bus, -EINVAL);
365 assert_return(bus->state == BUS_UNSET, -EPERM);
366 assert_return(!bus_pid_changed(bus), -ECHILD);
372 _public_ int sd_bus_set_description(sd_bus *bus, const char *description) {
373 assert_return(bus, -EINVAL);
374 assert_return(bus->state == BUS_UNSET, -EPERM);
375 assert_return(!bus_pid_changed(bus), -ECHILD);
377 return free_and_strdup(&bus->description, description);
381 _public_ int sd_bus_set_allow_interactive_authorization(sd_bus *bus, int b) {
382 assert_return(bus, -EINVAL);
383 assert_return(!bus_pid_changed(bus), -ECHILD);
385 bus->allow_interactive_authorization = !!b;
389 /// UNNEEDED by elogind
391 _public_ int sd_bus_get_allow_interactive_authorization(sd_bus *bus) {
392 assert_return(bus, -EINVAL);
393 assert_return(!bus_pid_changed(bus), -ECHILD);
395 return bus->allow_interactive_authorization;
399 static int hello_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
407 assert(bus->state == BUS_HELLO || bus->state == BUS_CLOSING);
409 r = sd_bus_message_get_errno(reply);
413 r = sd_bus_message_read(reply, "s", &s);
417 if (!service_name_is_valid(s) || s[0] != ':')
420 bus->unique_name = strdup(s);
421 if (!bus->unique_name)
424 if (bus->state == BUS_HELLO)
425 bus->state = BUS_RUNNING;
430 static int bus_send_hello(sd_bus *bus) {
431 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
436 if (!bus->bus_client || bus->is_kernel)
439 r = sd_bus_message_new_method_call(
442 "org.freedesktop.DBus",
443 "/org/freedesktop/DBus",
444 "org.freedesktop.DBus",
449 return sd_bus_call_async(bus, NULL, m, hello_callback, NULL, 0);
452 int bus_start_running(sd_bus *bus) {
455 if (bus->bus_client && !bus->is_kernel) {
456 bus->state = BUS_HELLO;
460 bus->state = BUS_RUNNING;
464 static int parse_address_key(const char **p, const char *key, char **value) {
465 size_t l, n = 0, allocated = 0;
475 if (strncmp(*p, key, l) != 0)
488 while (*a != ';' && *a != ',' && *a != 0) {
506 c = (char) ((x << 4) | y);
513 if (!GREEDY_REALLOC(r, allocated, n + 2))
537 static void skip_address_key(const char **p) {
541 *p += strcspn(*p, ",");
547 static int parse_unix_address(sd_bus *b, const char **p, char **guid) {
548 _cleanup_free_ char *path = NULL, *abstract = NULL;
557 while (**p != 0 && **p != ';') {
558 r = parse_address_key(p, "guid", guid);
564 r = parse_address_key(p, "path", &path);
570 r = parse_address_key(p, "abstract", &abstract);
579 if (!path && !abstract)
582 if (path && abstract)
587 if (l > sizeof(b->sockaddr.un.sun_path))
590 b->sockaddr.un.sun_family = AF_UNIX;
591 strncpy(b->sockaddr.un.sun_path, path, sizeof(b->sockaddr.un.sun_path));
592 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l;
593 } else if (abstract) {
594 l = strlen(abstract);
595 if (l > sizeof(b->sockaddr.un.sun_path) - 1)
598 b->sockaddr.un.sun_family = AF_UNIX;
599 b->sockaddr.un.sun_path[0] = 0;
600 strncpy(b->sockaddr.un.sun_path+1, abstract, sizeof(b->sockaddr.un.sun_path)-1);
601 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
607 static int parse_tcp_address(sd_bus *b, const char **p, char **guid) {
608 _cleanup_free_ char *host = NULL, *port = NULL, *family = NULL;
610 struct addrinfo *result, hints = {
611 .ai_socktype = SOCK_STREAM,
612 .ai_flags = AI_ADDRCONFIG,
620 while (**p != 0 && **p != ';') {
621 r = parse_address_key(p, "guid", guid);
627 r = parse_address_key(p, "host", &host);
633 r = parse_address_key(p, "port", &port);
639 r = parse_address_key(p, "family", &family);
652 if (streq(family, "ipv4"))
653 hints.ai_family = AF_INET;
654 else if (streq(family, "ipv6"))
655 hints.ai_family = AF_INET6;
660 r = getaddrinfo(host, port, &hints, &result);
664 return -EADDRNOTAVAIL;
666 memcpy(&b->sockaddr, result->ai_addr, result->ai_addrlen);
667 b->sockaddr_size = result->ai_addrlen;
669 freeaddrinfo(result);
674 static int parse_exec_address(sd_bus *b, const char **p, char **guid) {
676 unsigned n_argv = 0, j;
678 size_t allocated = 0;
686 while (**p != 0 && **p != ';') {
687 r = parse_address_key(p, "guid", guid);
693 r = parse_address_key(p, "path", &path);
699 if (startswith(*p, "argv")) {
703 ul = strtoul(*p + 4, (char**) p, 10);
704 if (errno > 0 || **p != '=' || ul > 256) {
712 if (!GREEDY_REALLOC0(argv, allocated, ul + 2)) {
720 r = parse_address_key(p, NULL, argv + ul);
735 /* Make sure there are no holes in the array, with the
736 * exception of argv[0] */
737 for (j = 1; j < n_argv; j++)
743 if (argv && argv[0] == NULL) {
744 argv[0] = strdup(path);
756 for (j = 0; j < n_argv; j++)
764 static int parse_kernel_address(sd_bus *b, const char **p, char **guid) {
765 _cleanup_free_ char *path = NULL;
773 while (**p != 0 && **p != ';') {
774 r = parse_address_key(p, "guid", guid);
780 r = parse_address_key(p, "path", &path);
799 static int parse_container_unix_address(sd_bus *b, const char **p, char **guid) {
800 _cleanup_free_ char *machine = NULL, *pid = NULL;
808 while (**p != 0 && **p != ';') {
809 r = parse_address_key(p, "guid", guid);
815 r = parse_address_key(p, "machine", &machine);
821 r = parse_address_key(p, "pid", &pid);
830 if (!machine == !pid)
834 if (!machine_name_is_valid(machine))
838 b->machine = machine;
841 b->machine = mfree(b->machine);
845 r = parse_pid(pid, &b->nspid);
851 b->sockaddr.un.sun_family = AF_UNIX;
852 strncpy(b->sockaddr.un.sun_path, "/var/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
853 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen("/var/run/dbus/system_bus_socket");
858 static int parse_container_kernel_address(sd_bus *b, const char **p, char **guid) {
859 _cleanup_free_ char *machine = NULL, *pid = NULL;
867 while (**p != 0 && **p != ';') {
868 r = parse_address_key(p, "guid", guid);
874 r = parse_address_key(p, "machine", &machine);
880 r = parse_address_key(p, "pid", &pid);
889 if (!machine == !pid)
893 if (!machine_name_is_valid(machine))
897 b->machine = machine;
900 b->machine = mfree(b->machine);
904 r = parse_pid(pid, &b->nspid);
910 r = free_and_strdup(&b->kernel, "/sys/fs/kdbus/0-system/bus");
917 static void bus_reset_parsed_address(sd_bus *b) {
921 b->sockaddr_size = 0;
922 b->exec_argv = strv_free(b->exec_argv);
923 b->exec_path = mfree(b->exec_path);
924 b->server_id = SD_ID128_NULL;
925 b->kernel = mfree(b->kernel);
926 b->machine = mfree(b->machine);
930 static int bus_parse_next_address(sd_bus *b) {
931 _cleanup_free_ char *guid = NULL;
939 if (b->address[b->address_index] == 0)
942 bus_reset_parsed_address(b);
944 a = b->address + b->address_index;
953 if (startswith(a, "unix:")) {
956 r = parse_unix_address(b, &a, &guid);
961 } else if (startswith(a, "tcp:")) {
964 r = parse_tcp_address(b, &a, &guid);
970 } else if (startswith(a, "unixexec:")) {
973 r = parse_exec_address(b, &a, &guid);
979 } else if (startswith(a, "kernel:")) {
982 r = parse_kernel_address(b, &a, &guid);
987 } else if (startswith(a, "x-machine-unix:")) {
990 r = parse_container_unix_address(b, &a, &guid);
995 } else if (startswith(a, "x-machine-kernel:")) {
998 r = parse_container_kernel_address(b, &a, &guid);
1011 r = sd_id128_from_string(guid, &b->server_id);
1016 b->address_index = a - b->address;
1020 static int bus_start_address(sd_bus *b) {
1021 bool container_kdbus_available = false;
1022 bool kdbus_available = false;
1028 bool skipped = false;
1033 * Usually, if you provide multiple different bus-addresses, we
1034 * try all of them in order. We use the first one that
1035 * succeeds. However, if you mix kernel and unix addresses, we
1036 * never try unix-addresses if a previous kernel address was
1037 * tried and kdbus was available. This is required to prevent
1038 * clients to fallback to the bus-proxy if kdbus is available
1039 * but failed (eg., too many connections).
1043 r = bus_socket_exec(b);
1044 else if ((b->nspid > 0 || b->machine) && b->kernel) {
1045 r = bus_container_connect_kernel(b);
1046 if (r < 0 && !IN_SET(r, -ENOENT, -ESOCKTNOSUPPORT))
1047 container_kdbus_available = true;
1049 } else if ((b->nspid > 0 || b->machine) && b->sockaddr.sa.sa_family != AF_UNSPEC) {
1050 if (!container_kdbus_available)
1051 r = bus_container_connect_socket(b);
1055 } else if (b->kernel) {
1056 r = bus_kernel_connect(b);
1057 if (r < 0 && !IN_SET(r, -ENOENT, -ESOCKTNOSUPPORT))
1058 kdbus_available = true;
1060 } else if (b->sockaddr.sa.sa_family != AF_UNSPEC) {
1061 if (!kdbus_available)
1062 r = bus_socket_connect(b);
1070 r = attach_io_events(b);
1075 b->last_connect_error = -r;
1078 r = bus_parse_next_address(b);
1082 return b->last_connect_error ? -b->last_connect_error : -ECONNREFUSED;
1086 int bus_next_address(sd_bus *b) {
1089 bus_reset_parsed_address(b);
1090 return bus_start_address(b);
1093 static int bus_start_fd(sd_bus *b) {
1098 assert(b->input_fd >= 0);
1099 assert(b->output_fd >= 0);
1101 r = fd_nonblock(b->input_fd, true);
1105 r = fd_cloexec(b->input_fd, true);
1109 if (b->input_fd != b->output_fd) {
1110 r = fd_nonblock(b->output_fd, true);
1114 r = fd_cloexec(b->output_fd, true);
1119 if (fstat(b->input_fd, &st) < 0)
1122 if (S_ISCHR(b->input_fd))
1123 return bus_kernel_take_fd(b);
1125 return bus_socket_take_fd(b);
1128 _public_ int sd_bus_start(sd_bus *bus) {
1131 assert_return(bus, -EINVAL);
1132 assert_return(bus->state == BUS_UNSET, -EPERM);
1133 assert_return(!bus_pid_changed(bus), -ECHILD);
1135 bus->state = BUS_OPENING;
1137 if (bus->is_server && bus->bus_client)
1140 if (bus->input_fd >= 0)
1141 r = bus_start_fd(bus);
1142 else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->kernel || bus->machine)
1143 r = bus_start_address(bus);
1152 return bus_send_hello(bus);
1155 _public_ int sd_bus_open(sd_bus **ret) {
1160 assert_return(ret, -EINVAL);
1162 /* Let's connect to the starter bus if it is set, and
1163 * otherwise to the bus that is appropropriate for the scope
1164 * we are running in */
1166 e = secure_getenv("DBUS_STARTER_BUS_TYPE");
1168 if (streq(e, "system"))
1169 return sd_bus_open_system(ret);
1170 /// elogind does not support systemd units
1172 else if (STR_IN_SET(e, "session", "user"))
1173 return sd_bus_open_user(ret);
1177 e = secure_getenv("DBUS_STARTER_ADDRESS");
1179 /// elogind does not support systemd units
1181 if (cg_pid_get_owner_uid(0, NULL) >= 0)
1182 return sd_bus_open_user(ret);
1185 return sd_bus_open_system(ret);
1192 r = sd_bus_set_address(b, e);
1196 b->bus_client = true;
1198 /* We don't know whether the bus is trusted or not, so better
1199 * be safe, and authenticate everything */
1201 b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1202 b->creds_mask |= SD_BUS_CREDS_UID | SD_BUS_CREDS_EUID | SD_BUS_CREDS_EFFECTIVE_CAPS;
1204 r = sd_bus_start(b);
1216 int bus_set_address_system(sd_bus *b) {
1220 e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1222 return sd_bus_set_address(b, e);
1224 return sd_bus_set_address(b, DEFAULT_SYSTEM_BUS_ADDRESS);
1227 _public_ int sd_bus_open_system(sd_bus **ret) {
1231 assert_return(ret, -EINVAL);
1237 r = bus_set_address_system(b);
1241 b->bus_client = true;
1242 b->is_system = true;
1244 /* Let's do per-method access control on the system bus. We
1245 * need the caller's UID and capability set for that. */
1247 b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1248 b->creds_mask |= SD_BUS_CREDS_UID | SD_BUS_CREDS_EUID | SD_BUS_CREDS_EFFECTIVE_CAPS;
1250 r = sd_bus_start(b);
1262 /// elogind can not open/use a user bus
1264 int bus_set_address_user(sd_bus *b) {
1271 e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
1273 return sd_bus_set_address(b, e);
1275 r = cg_pid_get_owner_uid(0, &uid);
1279 e = secure_getenv("XDG_RUNTIME_DIR");
1281 _cleanup_free_ char *ee = NULL;
1283 ee = bus_address_escape(e);
1287 (void) asprintf(&b->address, KERNEL_USER_BUS_ADDRESS_FMT ";" UNIX_USER_BUS_ADDRESS_FMT, uid, ee);
1289 (void) asprintf(&b->address, KERNEL_USER_BUS_ADDRESS_FMT, uid);
1298 _public_ int sd_bus_open_user(sd_bus **ret) {
1299 /// elogind does not support user buses
1304 assert_return(ret, -EINVAL);
1310 r = bus_set_address_user(b);
1314 b->bus_client = true;
1317 /* We don't do any per-method access control on the user
1321 r = sd_bus_start(b);
1332 return sd_bus_open_system(ret);
1336 int bus_set_address_system_remote(sd_bus *b, const char *host) {
1337 _cleanup_free_ char *e = NULL;
1338 char *m = NULL, *c = NULL;
1343 /* Let's see if we shall enter some container */
1344 m = strchr(host, ':');
1348 /* Let's make sure this is not a port of some kind,
1349 * and is a valid machine name. */
1350 if (!in_charset(m, "0123456789") && machine_name_is_valid(m)) {
1353 /* Cut out the host part */
1354 t = strndupa(host, m - host - 1);
1355 e = bus_address_escape(t);
1359 c = strjoina(",argv4=--machine=", m);
1364 e = bus_address_escape(host);
1369 b->address = strjoin("unixexec:path=ssh,argv1=-xT,argv2=", e, ",argv3=systemd-stdio-bridge", c, NULL);
1376 _public_ int sd_bus_open_system_remote(sd_bus **ret, const char *host) {
1380 assert_return(host, -EINVAL);
1381 assert_return(ret, -EINVAL);
1383 r = sd_bus_new(&bus);
1387 r = bus_set_address_system_remote(bus, host);
1391 bus->bus_client = true;
1392 bus->trusted = false;
1393 bus->is_system = true;
1395 r = sd_bus_start(bus);
1407 int bus_set_address_system_machine(sd_bus *b, const char *machine) {
1408 _cleanup_free_ char *e = NULL;
1413 e = bus_address_escape(machine);
1417 b->address = strjoin("x-machine-kernel:machine=", e, ";x-machine-unix:machine=", e, NULL);
1424 _public_ int sd_bus_open_system_machine(sd_bus **ret, const char *machine) {
1428 assert_return(machine, -EINVAL);
1429 assert_return(ret, -EINVAL);
1430 assert_return(machine_name_is_valid(machine), -EINVAL);
1432 r = sd_bus_new(&bus);
1436 r = bus_set_address_system_machine(bus, machine);
1440 bus->bus_client = true;
1441 bus->trusted = false;
1442 bus->is_system = true;
1444 r = sd_bus_start(bus);
1456 _public_ void sd_bus_close(sd_bus *bus) {
1460 if (bus->state == BUS_CLOSED)
1462 if (bus_pid_changed(bus))
1465 bus->state = BUS_CLOSED;
1467 sd_bus_detach_event(bus);
1469 /* Drop all queued messages so that they drop references to
1470 * the bus object and the bus may be freed */
1471 bus_reset_queues(bus);
1473 if (!bus->is_kernel)
1476 /* We'll leave the fd open in case this is a kernel bus, since
1477 * there might still be memblocks around that reference this
1478 * bus, and they might need to invoke the KDBUS_CMD_FREE
1479 * ioctl on the fd when they are freed. */
1482 _public_ sd_bus* sd_bus_flush_close_unref(sd_bus *bus) {
1490 return sd_bus_unref(bus);
1493 static void bus_enter_closing(sd_bus *bus) {
1496 if (bus->state != BUS_OPENING &&
1497 bus->state != BUS_AUTHENTICATING &&
1498 bus->state != BUS_HELLO &&
1499 bus->state != BUS_RUNNING)
1502 bus->state = BUS_CLOSING;
1505 _public_ sd_bus *sd_bus_ref(sd_bus *bus) {
1506 assert_return(bus, NULL);
1508 assert_se(REFCNT_INC(bus->n_ref) >= 2);
1513 _public_ sd_bus *sd_bus_unref(sd_bus *bus) {
1519 i = REFCNT_DEC(bus->n_ref);
1527 /// UNNEEDED by elogind
1529 _public_ int sd_bus_is_open(sd_bus *bus) {
1531 assert_return(bus, -EINVAL);
1532 assert_return(!bus_pid_changed(bus), -ECHILD);
1534 return BUS_IS_OPEN(bus->state);
1538 _public_ int sd_bus_can_send(sd_bus *bus, char type) {
1541 assert_return(bus, -EINVAL);
1542 assert_return(bus->state != BUS_UNSET, -ENOTCONN);
1543 assert_return(!bus_pid_changed(bus), -ECHILD);
1545 if (bus->hello_flags & KDBUS_HELLO_MONITOR)
1548 if (type == SD_BUS_TYPE_UNIX_FD) {
1549 if (!(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD))
1552 r = bus_ensure_running(bus);
1556 return bus->can_fds;
1559 return bus_type_is_valid(type);
1562 /// UNNEEDED by elogind
1564 _public_ int sd_bus_get_bus_id(sd_bus *bus, sd_id128_t *id) {
1567 assert_return(bus, -EINVAL);
1568 assert_return(id, -EINVAL);
1569 assert_return(!bus_pid_changed(bus), -ECHILD);
1571 r = bus_ensure_running(bus);
1575 *id = bus->server_id;
1580 static int bus_seal_message(sd_bus *b, sd_bus_message *m, usec_t timeout) {
1585 /* If we copy the same message to multiple
1586 * destinations, avoid using the same cookie
1588 b->cookie = MAX(b->cookie, BUS_MESSAGE_COOKIE(m));
1593 timeout = BUS_DEFAULT_TIMEOUT;
1595 return bus_message_seal(m, ++b->cookie, timeout);
1598 static int bus_remarshal_message(sd_bus *b, sd_bus_message **m) {
1599 bool remarshal = false;
1603 /* wrong packet version */
1604 if (b->message_version != 0 && b->message_version != (*m)->header->version)
1607 /* wrong packet endianness */
1608 if (b->message_endian != 0 && b->message_endian != (*m)->header->endian)
1611 /* TODO: kdbus-messages received from the kernel contain data which is
1612 * not allowed to be passed to KDBUS_CMD_SEND. Therefore, we have to
1613 * force remarshaling of the message. Technically, we could just
1614 * recreate the kdbus message, but that is non-trivial as other parts of
1615 * the message refer to m->kdbus already. This should be fixed! */
1616 if ((*m)->kdbus && (*m)->release_kdbus)
1619 return remarshal ? bus_message_remarshal(b, m) : 0;
1622 int bus_seal_synthetic_message(sd_bus *b, sd_bus_message *m) {
1626 /* Fake some timestamps, if they were requested, and not
1627 * already initialized */
1628 if (b->attach_flags & KDBUS_ATTACH_TIMESTAMP) {
1629 if (m->realtime <= 0)
1630 m->realtime = now(CLOCK_REALTIME);
1632 if (m->monotonic <= 0)
1633 m->monotonic = now(CLOCK_MONOTONIC);
1636 /* The bus specification says the serial number cannot be 0,
1637 * hence let's fill something in for synthetic messages. Since
1638 * synthetic messages might have a fake sender and we don't
1639 * want to interfere with the real sender's serial numbers we
1640 * pick a fixed, artificial one. We use (uint32_t) -1 rather
1641 * than (uint64_t) -1 since dbus1 only had 32bit identifiers,
1642 * even though kdbus can do 64bit. */
1643 return bus_message_seal(m, 0xFFFFFFFFULL, 0);
1646 static int bus_write_message(sd_bus *bus, sd_bus_message *m, bool hint_sync_call, size_t *idx) {
1653 r = bus_kernel_write_message(bus, m, hint_sync_call);
1655 r = bus_socket_write_message(bus, m, idx);
1660 if (bus->is_kernel || *idx >= BUS_MESSAGE_SIZE(m))
1661 log_debug("Sent message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%" PRIu64 " reply_cookie=%" PRIu64 " error=%s",
1662 bus_message_type_to_string(m->header->type),
1663 strna(sd_bus_message_get_sender(m)),
1664 strna(sd_bus_message_get_destination(m)),
1665 strna(sd_bus_message_get_path(m)),
1666 strna(sd_bus_message_get_interface(m)),
1667 strna(sd_bus_message_get_member(m)),
1668 BUS_MESSAGE_COOKIE(m),
1670 strna(m->error.message));
1675 static int dispatch_wqueue(sd_bus *bus) {
1679 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1681 while (bus->wqueue_size > 0) {
1683 r = bus_write_message(bus, bus->wqueue[0], false, &bus->windex);
1687 /* Didn't do anything this time */
1689 else if (bus->is_kernel || bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
1690 /* Fully written. Let's drop the entry from
1693 * This isn't particularly optimized, but
1694 * well, this is supposed to be our worst-case
1695 * buffer only, and the socket buffer is
1696 * supposed to be our primary buffer, and if
1697 * it got full, then all bets are off
1700 bus->wqueue_size --;
1701 sd_bus_message_unref(bus->wqueue[0]);
1702 memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
1712 static int bus_read_message(sd_bus *bus, bool hint_priority, int64_t priority) {
1716 return bus_kernel_read_message(bus, hint_priority, priority);
1718 return bus_socket_read_message(bus);
1721 int bus_rqueue_make_room(sd_bus *bus) {
1724 if (bus->rqueue_size >= BUS_RQUEUE_MAX)
1727 if (!GREEDY_REALLOC(bus->rqueue, bus->rqueue_allocated, bus->rqueue_size + 1))
1733 static int dispatch_rqueue(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **m) {
1738 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1740 /* Note that the priority logic is only available on kdbus,
1741 * where the rqueue is unused. We check the rqueue here
1742 * anyway, because it's simple... */
1745 if (bus->rqueue_size > 0) {
1746 /* Dispatch a queued message */
1748 *m = bus->rqueue[0];
1749 bus->rqueue_size --;
1750 memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
1754 /* Try to read a new message */
1755 r = bus_read_message(bus, hint_priority, priority);
1765 static int bus_send_internal(sd_bus *bus, sd_bus_message *_m, uint64_t *cookie, bool hint_sync_call) {
1766 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1769 assert_return(m, -EINVAL);
1774 assert_return(!bus_pid_changed(bus), -ECHILD);
1775 assert_return(!bus->is_kernel || !(bus->hello_flags & KDBUS_HELLO_MONITOR), -EROFS);
1777 if (!BUS_IS_OPEN(bus->state))
1781 r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
1788 /* If the cookie number isn't kept, then we know that no reply
1790 if (!cookie && !m->sealed)
1791 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1793 r = bus_seal_message(bus, m, 0);
1797 /* Remarshall if we have to. This will possibly unref the
1798 * message and place a replacement in m */
1799 r = bus_remarshal_message(bus, &m);
1803 /* If this is a reply and no reply was requested, then let's
1804 * suppress this, if we can */
1808 if ((bus->state == BUS_RUNNING || bus->state == BUS_HELLO) && bus->wqueue_size <= 0) {
1811 r = bus_write_message(bus, m, hint_sync_call, &idx);
1813 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
1814 bus_enter_closing(bus);
1821 if (!bus->is_kernel && idx < BUS_MESSAGE_SIZE(m)) {
1822 /* Wasn't fully written. So let's remember how
1823 * much was written. Note that the first entry
1824 * of the wqueue array is always allocated so
1825 * that we always can remember how much was
1827 bus->wqueue[0] = sd_bus_message_ref(m);
1828 bus->wqueue_size = 1;
1833 /* Just append it to the queue. */
1835 if (bus->wqueue_size >= BUS_WQUEUE_MAX)
1838 if (!GREEDY_REALLOC(bus->wqueue, bus->wqueue_allocated, bus->wqueue_size + 1))
1841 bus->wqueue[bus->wqueue_size ++] = sd_bus_message_ref(m);
1846 *cookie = BUS_MESSAGE_COOKIE(m);
1851 _public_ int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *cookie) {
1852 return bus_send_internal(bus, m, cookie, false);
1855 /// UNNEEDED by elogind
1857 _public_ int sd_bus_send_to(sd_bus *bus, sd_bus_message *m, const char *destination, uint64_t *cookie) {
1860 assert_return(m, -EINVAL);
1865 assert_return(!bus_pid_changed(bus), -ECHILD);
1867 if (!BUS_IS_OPEN(bus->state))
1870 if (!streq_ptr(m->destination, destination)) {
1875 r = sd_bus_message_set_destination(m, destination);
1880 return sd_bus_send(bus, m, cookie);
1884 static usec_t calc_elapse(uint64_t usec) {
1885 if (usec == (uint64_t) -1)
1888 return now(CLOCK_MONOTONIC) + usec;
1891 static int timeout_compare(const void *a, const void *b) {
1892 const struct reply_callback *x = a, *y = b;
1894 if (x->timeout != 0 && y->timeout == 0)
1897 if (x->timeout == 0 && y->timeout != 0)
1900 if (x->timeout < y->timeout)
1903 if (x->timeout > y->timeout)
1909 _public_ int sd_bus_call_async(
1913 sd_bus_message_handler_t callback,
1917 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1918 _cleanup_bus_slot_unref_ sd_bus_slot *s = NULL;
1921 assert_return(m, -EINVAL);
1922 assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1923 assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1924 assert_return(callback, -EINVAL);
1929 assert_return(!bus_pid_changed(bus), -ECHILD);
1930 assert_return(!bus->is_kernel || !(bus->hello_flags & KDBUS_HELLO_MONITOR), -EROFS);
1932 if (!BUS_IS_OPEN(bus->state))
1935 r = ordered_hashmap_ensure_allocated(&bus->reply_callbacks, &uint64_hash_ops);
1939 r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
1943 r = bus_seal_message(bus, m, usec);
1947 r = bus_remarshal_message(bus, &m);
1951 s = bus_slot_allocate(bus, !slot, BUS_REPLY_CALLBACK, sizeof(struct reply_callback), userdata);
1955 s->reply_callback.callback = callback;
1957 s->reply_callback.cookie = BUS_MESSAGE_COOKIE(m);
1958 r = ordered_hashmap_put(bus->reply_callbacks, &s->reply_callback.cookie, &s->reply_callback);
1960 s->reply_callback.cookie = 0;
1964 s->reply_callback.timeout = calc_elapse(m->timeout);
1965 if (s->reply_callback.timeout != 0) {
1966 r = prioq_put(bus->reply_callbacks_prioq, &s->reply_callback, &s->reply_callback.prioq_idx);
1968 s->reply_callback.timeout = 0;
1973 r = sd_bus_send(bus, m, &s->reply_callback.cookie);
1984 int bus_ensure_running(sd_bus *bus) {
1989 if (bus->state == BUS_UNSET || bus->state == BUS_CLOSED || bus->state == BUS_CLOSING)
1991 if (bus->state == BUS_RUNNING)
1995 r = sd_bus_process(bus, NULL);
1998 if (bus->state == BUS_RUNNING)
2003 r = sd_bus_wait(bus, (uint64_t) -1);
2009 _public_ int sd_bus_call(
2013 sd_bus_error *error,
2014 sd_bus_message **reply) {
2016 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
2022 bus_assert_return(m, -EINVAL, error);
2023 bus_assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL, error);
2024 bus_assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL, error);
2025 bus_assert_return(!bus_error_is_dirty(error), -EINVAL, error);
2030 bus_assert_return(!bus_pid_changed(bus), -ECHILD, error);
2031 bus_assert_return(!bus->is_kernel || !(bus->hello_flags & KDBUS_HELLO_MONITOR), -EROFS, error);
2033 if (!BUS_IS_OPEN(bus->state)) {
2038 r = bus_ensure_running(bus);
2042 i = bus->rqueue_size;
2044 r = bus_seal_message(bus, m, usec);
2048 r = bus_remarshal_message(bus, &m);
2052 r = bus_send_internal(bus, m, &cookie, true);
2056 timeout = calc_elapse(m->timeout);
2061 while (i < bus->rqueue_size) {
2062 sd_bus_message *incoming = NULL;
2064 incoming = bus->rqueue[i];
2066 if (incoming->reply_cookie == cookie) {
2067 /* Found a match! */
2069 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
2071 log_debug_bus_message(incoming);
2073 if (incoming->header->type == SD_BUS_MESSAGE_METHOD_RETURN) {
2075 if (incoming->n_fds <= 0 || (bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)) {
2079 sd_bus_message_unref(incoming);
2084 r = sd_bus_error_setf(error, SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Reply message contained file descriptors which I couldn't accept. Sorry.");
2085 sd_bus_message_unref(incoming);
2088 } else if (incoming->header->type == SD_BUS_MESSAGE_METHOD_ERROR) {
2089 r = sd_bus_error_copy(error, &incoming->error);
2090 sd_bus_message_unref(incoming);
2097 } else if (BUS_MESSAGE_COOKIE(incoming) == cookie &&
2100 streq(bus->unique_name, incoming->sender)) {
2102 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
2105 /* Our own message? Somebody is trying
2106 * to send its own client a message,
2107 * let's not dead-lock, let's fail
2110 sd_bus_message_unref(incoming);
2115 /* Try to read more, right-away */
2119 r = bus_read_message(bus, false, 0);
2121 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2122 bus_enter_closing(bus);
2134 n = now(CLOCK_MONOTONIC);
2142 left = (uint64_t) -1;
2144 r = bus_poll(bus, true, left);
2152 r = dispatch_wqueue(bus);
2154 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2155 bus_enter_closing(bus);
2164 return sd_bus_error_set_errno(error, r);
2167 /// UNNEEDED by elogind
2169 _public_ int sd_bus_get_fd(sd_bus *bus) {
2171 assert_return(bus, -EINVAL);
2172 assert_return(bus->input_fd == bus->output_fd, -EPERM);
2173 assert_return(!bus_pid_changed(bus), -ECHILD);
2175 return bus->input_fd;
2179 _public_ int sd_bus_get_events(sd_bus *bus) {
2182 assert_return(bus, -EINVAL);
2183 assert_return(!bus_pid_changed(bus), -ECHILD);
2185 if (!BUS_IS_OPEN(bus->state) && bus->state != BUS_CLOSING)
2188 if (bus->state == BUS_OPENING)
2190 else if (bus->state == BUS_AUTHENTICATING) {
2192 if (bus_socket_auth_needs_write(bus))
2197 } else if (bus->state == BUS_RUNNING || bus->state == BUS_HELLO) {
2198 if (bus->rqueue_size <= 0)
2200 if (bus->wqueue_size > 0)
2207 _public_ int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
2208 struct reply_callback *c;
2210 assert_return(bus, -EINVAL);
2211 assert_return(timeout_usec, -EINVAL);
2212 assert_return(!bus_pid_changed(bus), -ECHILD);
2214 if (!BUS_IS_OPEN(bus->state) && bus->state != BUS_CLOSING)
2217 if (bus->track_queue) {
2222 if (bus->state == BUS_CLOSING) {
2227 if (bus->state == BUS_AUTHENTICATING) {
2228 *timeout_usec = bus->auth_timeout;
2232 if (bus->state != BUS_RUNNING && bus->state != BUS_HELLO) {
2233 *timeout_usec = (uint64_t) -1;
2237 if (bus->rqueue_size > 0) {
2242 c = prioq_peek(bus->reply_callbacks_prioq);
2244 *timeout_usec = (uint64_t) -1;
2248 if (c->timeout == 0) {
2249 *timeout_usec = (uint64_t) -1;
2253 *timeout_usec = c->timeout;
2257 static int process_timeout(sd_bus *bus) {
2258 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2259 _cleanup_bus_message_unref_ sd_bus_message* m = NULL;
2260 struct reply_callback *c;
2267 c = prioq_peek(bus->reply_callbacks_prioq);
2271 n = now(CLOCK_MONOTONIC);
2275 r = bus_message_new_synthetic_error(
2278 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
2283 r = bus_seal_synthetic_message(bus, m);
2287 assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
2290 ordered_hashmap_remove(bus->reply_callbacks, &c->cookie);
2293 slot = container_of(c, sd_bus_slot, reply_callback);
2295 bus->iteration_counter ++;
2297 bus->current_message = m;
2298 bus->current_slot = sd_bus_slot_ref(slot);
2299 bus->current_handler = c->callback;
2300 bus->current_userdata = slot->userdata;
2301 r = c->callback(m, slot->userdata, &error_buffer);
2302 bus->current_userdata = NULL;
2303 bus->current_handler = NULL;
2304 bus->current_slot = NULL;
2305 bus->current_message = NULL;
2307 if (slot->floating) {
2308 bus_slot_disconnect(slot);
2309 sd_bus_slot_unref(slot);
2312 sd_bus_slot_unref(slot);
2314 return bus_maybe_reply_error(m, r, &error_buffer);
2317 static int process_hello(sd_bus *bus, sd_bus_message *m) {
2321 if (bus->state != BUS_HELLO)
2324 /* Let's make sure the first message on the bus is the HELLO
2325 * reply. But note that we don't actually parse the message
2326 * here (we leave that to the usual handling), we just verify
2327 * we don't let any earlier msg through. */
2329 if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2330 m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2333 if (m->reply_cookie != 1)
2339 static int process_reply(sd_bus *bus, sd_bus_message *m) {
2340 _cleanup_bus_message_unref_ sd_bus_message *synthetic_reply = NULL;
2341 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2342 struct reply_callback *c;
2349 if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2350 m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2353 if (bus->is_kernel && (bus->hello_flags & KDBUS_HELLO_MONITOR))
2356 if (m->destination && bus->unique_name && !streq_ptr(m->destination, bus->unique_name))
2359 c = ordered_hashmap_remove(bus->reply_callbacks, &m->reply_cookie);
2365 slot = container_of(c, sd_bus_slot, reply_callback);
2367 if (m->n_fds > 0 && !(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)) {
2369 /* If the reply contained a file descriptor which we
2370 * didn't want we pass an error instead. */
2372 r = bus_message_new_synthetic_error(
2375 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Reply message contained file descriptor"),
2380 /* Copy over original timestamp */
2381 synthetic_reply->realtime = m->realtime;
2382 synthetic_reply->monotonic = m->monotonic;
2383 synthetic_reply->seqnum = m->seqnum;
2385 r = bus_seal_synthetic_message(bus, synthetic_reply);
2389 m = synthetic_reply;
2391 r = sd_bus_message_rewind(m, true);
2396 if (c->timeout != 0) {
2397 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2401 bus->current_slot = sd_bus_slot_ref(slot);
2402 bus->current_handler = c->callback;
2403 bus->current_userdata = slot->userdata;
2404 r = c->callback(m, slot->userdata, &error_buffer);
2405 bus->current_userdata = NULL;
2406 bus->current_handler = NULL;
2407 bus->current_slot = NULL;
2409 if (slot->floating) {
2410 bus_slot_disconnect(slot);
2411 sd_bus_slot_unref(slot);
2414 sd_bus_slot_unref(slot);
2416 return bus_maybe_reply_error(m, r, &error_buffer);
2419 static int process_filter(sd_bus *bus, sd_bus_message *m) {
2420 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2421 struct filter_callback *l;
2428 bus->filter_callbacks_modified = false;
2430 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
2433 if (bus->filter_callbacks_modified)
2436 /* Don't run this more than once per iteration */
2437 if (l->last_iteration == bus->iteration_counter)
2440 l->last_iteration = bus->iteration_counter;
2442 r = sd_bus_message_rewind(m, true);
2446 slot = container_of(l, sd_bus_slot, filter_callback);
2448 bus->current_slot = sd_bus_slot_ref(slot);
2449 bus->current_handler = l->callback;
2450 bus->current_userdata = slot->userdata;
2451 r = l->callback(m, slot->userdata, &error_buffer);
2452 bus->current_userdata = NULL;
2453 bus->current_handler = NULL;
2454 bus->current_slot = sd_bus_slot_unref(slot);
2456 r = bus_maybe_reply_error(m, r, &error_buffer);
2462 } while (bus->filter_callbacks_modified);
2467 static int process_match(sd_bus *bus, sd_bus_message *m) {
2474 bus->match_callbacks_modified = false;
2476 r = bus_match_run(bus, &bus->match_callbacks, m);
2480 } while (bus->match_callbacks_modified);
2485 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
2486 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2492 if (bus->hello_flags & KDBUS_HELLO_MONITOR)
2495 if (bus->manual_peer_interface)
2498 if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2501 if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2504 if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2507 if (streq_ptr(m->member, "Ping"))
2508 r = sd_bus_message_new_method_return(m, &reply);
2509 else if (streq_ptr(m->member, "GetMachineId")) {
2513 r = sd_id128_get_machine(&id);
2517 r = sd_bus_message_new_method_return(m, &reply);
2521 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2523 r = sd_bus_message_new_method_errorf(
2525 SD_BUS_ERROR_UNKNOWN_METHOD,
2526 "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2532 r = sd_bus_send(bus, reply, NULL);
2539 static int process_fd_check(sd_bus *bus, sd_bus_message *m) {
2543 /* If we got a message with a file descriptor which we didn't
2544 * want to accept, then let's drop it. How can this even
2545 * happen? For example, when the kernel queues a message into
2546 * an activatable names's queue which allows fds, and then is
2547 * delivered to us later even though we ourselves did not
2550 if (bus->hello_flags & KDBUS_HELLO_MONITOR)
2556 if (bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)
2559 if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2560 return 1; /* just eat it up */
2562 return sd_bus_reply_method_errorf(m, SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Message contains file descriptors, which I cannot accept. Sorry.");
2565 static int process_message(sd_bus *bus, sd_bus_message *m) {
2571 bus->current_message = m;
2572 bus->iteration_counter++;
2574 log_debug_bus_message(m);
2576 r = process_hello(bus, m);
2580 r = process_reply(bus, m);
2584 r = process_fd_check(bus, m);
2588 r = process_filter(bus, m);
2592 r = process_match(bus, m);
2596 r = process_builtin(bus, m);
2600 r = bus_process_object(bus, m);
2603 bus->current_message = NULL;
2607 static int dispatch_track(sd_bus *bus) {
2610 if (!bus->track_queue)
2613 bus_track_dispatch(bus->track_queue);
2617 static int process_running(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2618 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2622 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
2624 r = process_timeout(bus);
2628 r = dispatch_wqueue(bus);
2632 r = dispatch_track(bus);
2636 r = dispatch_rqueue(bus, hint_priority, priority, &m);
2642 r = process_message(bus, m);
2647 r = sd_bus_message_rewind(m, true);
2656 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2658 log_debug("Unprocessed message call sender=%s object=%s interface=%s member=%s",
2659 strna(sd_bus_message_get_sender(m)),
2660 strna(sd_bus_message_get_path(m)),
2661 strna(sd_bus_message_get_interface(m)),
2662 strna(sd_bus_message_get_member(m)));
2664 r = sd_bus_reply_method_errorf(
2666 SD_BUS_ERROR_UNKNOWN_OBJECT,
2667 "Unknown object '%s'.", m->path);
2681 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2682 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2683 struct reply_callback *c;
2687 assert(bus->state == BUS_CLOSING);
2689 c = ordered_hashmap_first(bus->reply_callbacks);
2691 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2694 /* First, fail all outstanding method calls */
2695 r = bus_message_new_synthetic_error(
2698 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2703 r = bus_seal_synthetic_message(bus, m);
2707 if (c->timeout != 0) {
2708 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2712 ordered_hashmap_remove(bus->reply_callbacks, &c->cookie);
2715 slot = container_of(c, sd_bus_slot, reply_callback);
2717 bus->iteration_counter++;
2719 bus->current_message = m;
2720 bus->current_slot = sd_bus_slot_ref(slot);
2721 bus->current_handler = c->callback;
2722 bus->current_userdata = slot->userdata;
2723 r = c->callback(m, slot->userdata, &error_buffer);
2724 bus->current_userdata = NULL;
2725 bus->current_handler = NULL;
2726 bus->current_slot = NULL;
2727 bus->current_message = NULL;
2729 if (slot->floating) {
2730 bus_slot_disconnect(slot);
2731 sd_bus_slot_unref(slot);
2734 sd_bus_slot_unref(slot);
2736 return bus_maybe_reply_error(m, r, &error_buffer);
2739 /* Then, synthesize a Disconnected message */
2740 r = sd_bus_message_new_signal(
2743 "/org/freedesktop/DBus/Local",
2744 "org.freedesktop.DBus.Local",
2749 bus_message_set_sender_local(bus, m);
2751 r = bus_seal_synthetic_message(bus, m);
2757 bus->current_message = m;
2758 bus->iteration_counter++;
2760 r = process_filter(bus, m);
2764 r = process_match(bus, m);
2776 bus->current_message = NULL;
2781 static int bus_process_internal(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2782 BUS_DONT_DESTROY(bus);
2785 /* Returns 0 when we didn't do anything. This should cause the
2786 * caller to invoke sd_bus_wait() before returning the next
2787 * time. Returns > 0 when we did something, which possibly
2788 * means *ret is filled in with an unprocessed message. */
2790 assert_return(bus, -EINVAL);
2791 assert_return(!bus_pid_changed(bus), -ECHILD);
2793 /* We don't allow recursively invoking sd_bus_process(). */
2794 assert_return(!bus->current_message, -EBUSY);
2795 assert(!bus->current_slot);
2797 switch (bus->state) {
2806 r = bus_socket_process_opening(bus);
2807 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2808 bus_enter_closing(bus);
2816 case BUS_AUTHENTICATING:
2817 r = bus_socket_process_authenticating(bus);
2818 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2819 bus_enter_closing(bus);
2831 r = process_running(bus, hint_priority, priority, ret);
2832 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2833 bus_enter_closing(bus);
2843 return process_closing(bus, ret);
2846 assert_not_reached("Unknown state");
2849 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2850 return bus_process_internal(bus, false, 0, ret);
2853 /// UNNEEDED by elogind
2855 _public_ int sd_bus_process_priority(sd_bus *bus, int64_t priority, sd_bus_message **ret) {
2856 return bus_process_internal(bus, true, priority, ret);
2860 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2861 struct pollfd p[2] = {};
2864 usec_t m = USEC_INFINITY;
2868 if (bus->state == BUS_CLOSING)
2871 if (!BUS_IS_OPEN(bus->state))
2874 e = sd_bus_get_events(bus);
2879 /* The caller really needs some more data, he doesn't
2880 * care about what's already read, or any timeouts
2881 * except its own. */
2885 /* The caller wants to process if there's something to
2886 * process, but doesn't care otherwise */
2888 r = sd_bus_get_timeout(bus, &until);
2893 nw = now(CLOCK_MONOTONIC);
2894 m = until > nw ? until - nw : 0;
2898 if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
2901 p[0].fd = bus->input_fd;
2902 if (bus->output_fd == bus->input_fd) {
2906 p[0].events = e & POLLIN;
2907 p[1].fd = bus->output_fd;
2908 p[1].events = e & POLLOUT;
2912 r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
2916 return r > 0 ? 1 : 0;
2919 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
2921 assert_return(bus, -EINVAL);
2922 assert_return(!bus_pid_changed(bus), -ECHILD);
2924 if (bus->state == BUS_CLOSING)
2927 if (!BUS_IS_OPEN(bus->state))
2930 if (bus->rqueue_size > 0)
2933 return bus_poll(bus, false, timeout_usec);
2936 _public_ int sd_bus_flush(sd_bus *bus) {
2939 assert_return(bus, -EINVAL);
2940 assert_return(!bus_pid_changed(bus), -ECHILD);
2942 if (bus->state == BUS_CLOSING)
2945 if (!BUS_IS_OPEN(bus->state))
2948 r = bus_ensure_running(bus);
2952 if (bus->wqueue_size <= 0)
2956 r = dispatch_wqueue(bus);
2958 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2959 bus_enter_closing(bus);
2966 if (bus->wqueue_size <= 0)
2969 r = bus_poll(bus, false, (uint64_t) -1);
2975 /// UNNEEDED by elogind
2977 _public_ int sd_bus_add_filter(
2980 sd_bus_message_handler_t callback,
2985 assert_return(bus, -EINVAL);
2986 assert_return(callback, -EINVAL);
2987 assert_return(!bus_pid_changed(bus), -ECHILD);
2989 s = bus_slot_allocate(bus, !slot, BUS_FILTER_CALLBACK, sizeof(struct filter_callback), userdata);
2993 s->filter_callback.callback = callback;
2995 bus->filter_callbacks_modified = true;
2996 LIST_PREPEND(callbacks, bus->filter_callbacks, &s->filter_callback);
3005 _public_ int sd_bus_add_match(
3009 sd_bus_message_handler_t callback,
3012 struct bus_match_component *components = NULL;
3013 unsigned n_components = 0;
3014 sd_bus_slot *s = NULL;
3017 assert_return(bus, -EINVAL);
3018 assert_return(match, -EINVAL);
3019 assert_return(!bus_pid_changed(bus), -ECHILD);
3021 r = bus_match_parse(match, &components, &n_components);
3025 s = bus_slot_allocate(bus, !slot, BUS_MATCH_CALLBACK, sizeof(struct match_callback), userdata);
3031 s->match_callback.callback = callback;
3032 s->match_callback.cookie = ++bus->match_cookie;
3034 if (bus->bus_client) {
3035 enum bus_match_scope scope;
3037 scope = bus_match_get_scope(components, n_components);
3039 /* Do not install server-side matches for matches
3040 * against the local service, interface or bus
3042 if (scope != BUS_MATCH_LOCAL) {
3044 if (!bus->is_kernel) {
3045 /* When this is not a kernel transport, we
3046 * store the original match string, so that we
3047 * can use it to remove the match again */
3049 s->match_callback.match_string = strdup(match);
3050 if (!s->match_callback.match_string) {
3056 r = bus_add_match_internal(bus, s->match_callback.match_string, components, n_components, s->match_callback.cookie);
3060 s->match_added = true;
3064 bus->match_callbacks_modified = true;
3065 r = bus_match_add(&bus->match_callbacks, components, n_components, &s->match_callback);
3074 bus_match_parse_free(components, n_components);
3075 sd_bus_slot_unref(s);
3080 /// UNNEEDED by elogind
3082 int bus_remove_match_by_string(
3085 sd_bus_message_handler_t callback,
3088 struct bus_match_component *components = NULL;
3089 unsigned n_components = 0;
3090 struct match_callback *c;
3093 assert_return(bus, -EINVAL);
3094 assert_return(match, -EINVAL);
3095 assert_return(!bus_pid_changed(bus), -ECHILD);
3097 r = bus_match_parse(match, &components, &n_components);
3101 r = bus_match_find(&bus->match_callbacks, components, n_components, NULL, NULL, &c);
3105 sd_bus_slot_unref(container_of(c, sd_bus_slot, match_callback));
3108 bus_match_parse_free(components, n_components);
3114 bool bus_pid_changed(sd_bus *bus) {
3117 /* We don't support people creating a bus connection and
3118 * keeping it around over a fork(). Let's complain. */
3120 return bus->original_pid != getpid();
3123 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
3124 sd_bus *bus = userdata;
3129 r = sd_bus_process(bus, NULL);
3136 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
3137 sd_bus *bus = userdata;
3142 r = sd_bus_process(bus, NULL);
3149 static int prepare_callback(sd_event_source *s, void *userdata) {
3150 sd_bus *bus = userdata;
3157 e = sd_bus_get_events(bus);
3161 if (bus->output_fd != bus->input_fd) {
3163 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
3167 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
3171 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
3176 r = sd_bus_get_timeout(bus, &until);
3182 j = sd_event_source_set_time(bus->time_event_source, until);
3187 r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
3194 static int quit_callback(sd_event_source *event, void *userdata) {
3195 sd_bus *bus = userdata;
3205 static int attach_io_events(sd_bus *bus) {
3210 if (bus->input_fd < 0)
3216 if (!bus->input_io_event_source) {
3217 r = sd_event_add_io(bus->event, &bus->input_io_event_source, bus->input_fd, 0, io_callback, bus);
3221 r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
3225 r = sd_event_source_set_priority(bus->input_io_event_source, bus->event_priority);
3229 r = sd_event_source_set_description(bus->input_io_event_source, "bus-input");
3231 r = sd_event_source_set_io_fd(bus->input_io_event_source, bus->input_fd);
3236 if (bus->output_fd != bus->input_fd) {
3237 assert(bus->output_fd >= 0);
3239 if (!bus->output_io_event_source) {
3240 r = sd_event_add_io(bus->event, &bus->output_io_event_source, bus->output_fd, 0, io_callback, bus);
3244 r = sd_event_source_set_priority(bus->output_io_event_source, bus->event_priority);
3248 r = sd_event_source_set_description(bus->input_io_event_source, "bus-output");
3250 r = sd_event_source_set_io_fd(bus->output_io_event_source, bus->output_fd);
3259 static void detach_io_events(sd_bus *bus) {
3262 if (bus->input_io_event_source) {
3263 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
3264 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
3267 if (bus->output_io_event_source) {
3268 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
3269 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
3273 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
3276 assert_return(bus, -EINVAL);
3277 assert_return(!bus->event, -EBUSY);
3279 assert(!bus->input_io_event_source);
3280 assert(!bus->output_io_event_source);
3281 assert(!bus->time_event_source);
3284 bus->event = sd_event_ref(event);
3286 r = sd_event_default(&bus->event);
3291 bus->event_priority = priority;
3293 r = sd_event_add_time(bus->event, &bus->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, bus);
3297 r = sd_event_source_set_priority(bus->time_event_source, priority);
3301 r = sd_event_source_set_description(bus->time_event_source, "bus-time");
3305 r = sd_event_add_exit(bus->event, &bus->quit_event_source, quit_callback, bus);
3309 r = sd_event_source_set_description(bus->quit_event_source, "bus-exit");
3313 r = attach_io_events(bus);
3320 sd_bus_detach_event(bus);
3324 _public_ int sd_bus_detach_event(sd_bus *bus) {
3325 assert_return(bus, -EINVAL);
3330 detach_io_events(bus);
3332 if (bus->time_event_source) {
3333 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
3334 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
3337 if (bus->quit_event_source) {
3338 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
3339 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
3342 bus->event = sd_event_unref(bus->event);
3346 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
3347 assert_return(bus, NULL);
3352 _public_ sd_bus_message* sd_bus_get_current_message(sd_bus *bus) {
3353 assert_return(bus, NULL);
3355 return bus->current_message;
3358 /// UNNEEDED by elogind
3360 _public_ sd_bus_slot* sd_bus_get_current_slot(sd_bus *bus) {
3361 assert_return(bus, NULL);
3363 return bus->current_slot;
3367 _public_ sd_bus_message_handler_t sd_bus_get_current_handler(sd_bus *bus) {
3368 assert_return(bus, NULL);
3370 return bus->current_handler;
3373 _public_ void* sd_bus_get_current_userdata(sd_bus *bus) {
3374 assert_return(bus, NULL);
3376 return bus->current_userdata;
3379 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
3384 assert(default_bus);
3387 return !!*default_bus;
3390 *ret = sd_bus_ref(*default_bus);
3398 b->default_bus_ptr = default_bus;
3406 _public_ int sd_bus_default_system(sd_bus **ret) {
3407 return bus_default(sd_bus_open_system, &default_system_bus, ret);
3411 _public_ int sd_bus_default_user(sd_bus **ret) {
3412 /// elogind does not support user buses
3414 return bus_default(sd_bus_open_user, &default_user_bus, ret);
3416 return sd_bus_default_system(ret);
3420 _public_ int sd_bus_default(sd_bus **ret) {
3424 /* Let's try our best to reuse another cached connection. If
3425 * the starter bus type is set, connect via our normal
3426 * connection logic, ignoring $DBUS_STARTER_ADDRESS, so that
3427 * we can share the connection with the user/system default
3430 e = secure_getenv("DBUS_STARTER_BUS_TYPE");
3432 if (streq(e, "system"))
3433 return sd_bus_default_system(ret);
3434 /// elogind does not support systemd units
3436 else if (STR_IN_SET(e, "user", "session"))
3437 return sd_bus_default_user(ret);
3441 /* No type is specified, so we have not other option than to
3442 * use the starter address if it is set. */
3444 e = secure_getenv("DBUS_STARTER_ADDRESS");
3447 return bus_default(sd_bus_open, &default_starter_bus, ret);
3450 /* Finally, if nothing is set use the cached connection for
3451 * the right scope */
3453 /// elogind does not support systemd units
3455 if (cg_pid_get_owner_uid(0, NULL) >= 0)
3456 return sd_bus_default_user(ret);
3459 return sd_bus_default_system(ret);
3462 /// UNNEEDED by elogind
3464 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
3465 assert_return(b, -EINVAL);
3466 assert_return(tid, -EINVAL);
3467 assert_return(!bus_pid_changed(b), -ECHILD);
3475 return sd_event_get_tid(b->event, tid);
3480 _public_ int sd_bus_path_encode(const char *prefix, const char *external_id, char **ret_path) {
3481 _cleanup_free_ char *e = NULL;
3484 assert_return(object_path_is_valid(prefix), -EINVAL);
3485 assert_return(external_id, -EINVAL);
3486 assert_return(ret_path, -EINVAL);
3488 e = bus_label_escape(external_id);
3492 ret = strjoin(prefix, "/", e, NULL);
3500 _public_ int sd_bus_path_decode(const char *path, const char *prefix, char **external_id) {
3504 assert_return(object_path_is_valid(path), -EINVAL);
3505 assert_return(object_path_is_valid(prefix), -EINVAL);
3506 assert_return(external_id, -EINVAL);
3508 e = object_path_startswith(path, prefix);
3510 *external_id = NULL;
3514 ret = bus_label_unescape(e);
3522 _public_ int sd_bus_path_encode_many(char **out, const char *path_template, ...) {
3523 _cleanup_strv_free_ char **labels = NULL;
3524 char *path, *path_pos, **label_pos;
3525 const char *sep, *template_pos;
3530 assert_return(out, -EINVAL);
3531 assert_return(path_template, -EINVAL);
3533 path_length = strlen(path_template);
3535 va_start(list, path_template);
3536 for (sep = strchr(path_template, '%'); sep; sep = strchr(sep + 1, '%')) {
3540 arg = va_arg(list, const char *);
3546 label = bus_label_escape(arg);
3552 r = strv_consume(&labels, label);
3558 /* add label length, but account for the format character */
3559 path_length += strlen(label) - 1;
3563 path = malloc(path_length + 1);
3570 for (template_pos = path_template; *template_pos; ) {
3571 sep = strchrnul(template_pos, '%');
3572 path_pos = mempcpy(path_pos, template_pos, sep - template_pos);
3576 path_pos = stpcpy(path_pos, *label_pos++);
3577 template_pos = sep + 1;
3585 _public_ int sd_bus_path_decode_many(const char *path, const char *path_template, ...) {
3586 _cleanup_strv_free_ char **labels = NULL;
3587 const char *template_pos, *path_pos;
3593 * This decodes an object-path based on a template argument. The
3594 * template consists of a verbatim path, optionally including special
3597 * - Each occurrence of '%' in the template matches an arbitrary
3598 * substring of a label in the given path. At most one such
3599 * directive is allowed per label. For each such directive, the
3600 * caller must provide an output parameter (char **) via va_arg. If
3601 * NULL is passed, the given label is verified, but not returned.
3602 * For each matched label, the *decoded* label is stored in the
3603 * passed output argument, and the caller is responsible to free
3604 * it. Note that the output arguments are only modified if the
3605 * actualy path matched the template. Otherwise, they're left
3608 * This function returns <0 on error, 0 if the path does not match the
3609 * template, 1 if it matched.
3612 assert_return(path, -EINVAL);
3613 assert_return(path_template, -EINVAL);
3617 for (template_pos = path_template; *template_pos; ) {
3622 /* verify everything until the next '%' matches verbatim */
3623 sep = strchrnul(template_pos, '%');
3624 length = sep - template_pos;
3625 if (strncmp(path_pos, template_pos, length))
3629 template_pos += length;
3634 /* We found the next '%' character. Everything up until here
3635 * matched. We now skip ahead to the end of this label and make
3636 * sure it matches the tail of the label in the path. Then we
3637 * decode the string in-between and save it for later use. */
3639 ++template_pos; /* skip over '%' */
3641 sep = strchrnul(template_pos, '/');
3642 length = sep - template_pos; /* length of suffix to match verbatim */
3644 /* verify the suffixes match */
3645 sep = strchrnul(path_pos, '/');
3646 if (sep - path_pos < (ssize_t)length ||
3647 strncmp(sep - length, template_pos, length))
3650 template_pos += length; /* skip over matched label */
3651 length = sep - path_pos - length; /* length of sub-label to decode */
3653 /* store unescaped label for later use */
3654 label = bus_label_unescape_n(path_pos, length);
3658 r = strv_consume(&labels, label);
3662 path_pos = sep; /* skip decoded label and suffix */
3665 /* end of template must match end of path */
3669 /* copy the labels over to the caller */
3670 va_start(list, path_template);
3671 for (label_pos = labels; label_pos && *label_pos; ++label_pos) {
3674 arg = va_arg(list, char **);
3687 _public_ int sd_bus_try_close(sd_bus *bus) {
3690 assert_return(bus, -EINVAL);
3691 assert_return(!bus_pid_changed(bus), -ECHILD);
3693 if (!bus->is_kernel)
3696 if (!BUS_IS_OPEN(bus->state))
3699 if (bus->rqueue_size > 0)
3702 if (bus->wqueue_size > 0)
3705 r = bus_kernel_try_close(bus);
3713 _public_ int sd_bus_get_description(sd_bus *bus, const char **description) {
3714 assert_return(bus, -EINVAL);
3715 assert_return(description, -EINVAL);
3716 assert_return(bus->description, -ENXIO);
3717 assert_return(!bus_pid_changed(bus), -ECHILD);
3719 *description = bus->description;
3724 int bus_get_root_path(sd_bus *bus) {
3727 if (bus->cgroup_root)
3730 r = cg_get_root_path(&bus->cgroup_root);
3732 bus->cgroup_root = strdup("/");
3733 if (!bus->cgroup_root)
3742 /// UNNEEDED by elogind
3744 _public_ int sd_bus_get_scope(sd_bus *bus, const char **scope) {
3747 assert_return(bus, -EINVAL);
3748 assert_return(scope, -EINVAL);
3749 assert_return(!bus_pid_changed(bus), -ECHILD);
3751 if (bus->is_kernel) {
3752 _cleanup_free_ char *n = NULL;
3755 r = bus_kernel_get_bus_name(bus, &n);
3759 if (streq(n, "0-system")) {
3764 dash = strchr(n, '-');
3765 if (streq_ptr(dash, "-user")) {
3776 if (bus->is_system) {
3784 _public_ int sd_bus_get_address(sd_bus *bus, const char **address) {
3786 assert_return(bus, -EINVAL);
3787 assert_return(address, -EINVAL);
3788 assert_return(!bus_pid_changed(bus), -ECHILD);
3791 *address = bus->address;
3798 _public_ int sd_bus_get_creds_mask(sd_bus *bus, uint64_t *mask) {
3799 assert_return(bus, -EINVAL);
3800 assert_return(mask, -EINVAL);
3801 assert_return(!bus_pid_changed(bus), -ECHILD);
3803 *mask = bus->creds_mask;
3807 _public_ int sd_bus_is_bus_client(sd_bus *bus) {
3808 assert_return(bus, -EINVAL);
3809 assert_return(!bus_pid_changed(bus), -ECHILD);
3811 return bus->bus_client;
3814 _public_ int sd_bus_is_server(sd_bus *bus) {
3815 assert_return(bus, -EINVAL);
3816 assert_return(!bus_pid_changed(bus), -ECHILD);
3818 return bus->is_server;
3821 _public_ int sd_bus_is_anonymous(sd_bus *bus) {
3822 assert_return(bus, -EINVAL);
3823 assert_return(!bus_pid_changed(bus), -ECHILD);
3825 return bus->anonymous_auth;
3828 _public_ int sd_bus_is_trusted(sd_bus *bus) {
3829 assert_return(bus, -EINVAL);
3830 assert_return(!bus_pid_changed(bus), -ECHILD);
3832 return bus->trusted;
3835 _public_ int sd_bus_is_monitor(sd_bus *bus) {
3836 assert_return(bus, -EINVAL);
3837 assert_return(!bus_pid_changed(bus), -ECHILD);
3839 return !!(bus->hello_flags & KDBUS_HELLO_MONITOR);
3842 static void flush_close(sd_bus *bus) {
3846 /* Flushes and closes the specified bus. We take a ref before,
3847 * to ensure the flushing does not cause the bus to be
3850 sd_bus_flush_close_unref(sd_bus_ref(bus));
3853 _public_ void sd_bus_default_flush_close(void) {
3854 flush_close(default_starter_bus);
3855 flush_close(default_user_bus);
3856 flush_close(default_system_bus);