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/>.
40 #include "bus-internal.h"
41 #include "bus-message.h"
43 #include "bus-socket.h"
44 #include "bus-kernel.h"
45 #include "bus-control.h"
46 #include "bus-introspect.h"
47 #include "bus-signature.h"
48 #include "bus-objects.h"
50 #include "bus-container.h"
51 #include "bus-protocol.h"
53 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec);
54 static int attach_io_events(sd_bus *b);
55 static void detach_io_events(sd_bus *b);
57 static void bus_close_fds(sd_bus *b) {
63 close_nointr_nofail(b->input_fd);
65 if (b->output_fd >= 0 && b->output_fd != b->input_fd)
66 close_nointr_nofail(b->output_fd);
68 b->input_fd = b->output_fd = -1;
71 static void bus_node_destroy(sd_bus *b, struct node *n) {
72 struct node_callback *c;
73 struct node_vtable *v;
74 struct node_enumerator *e;
82 bus_node_destroy(b, n->child);
84 while ((c = n->callbacks)) {
85 LIST_REMOVE(callbacks, n->callbacks, c);
89 while ((v = n->vtables)) {
90 LIST_REMOVE(vtables, n->vtables, v);
95 while ((e = n->enumerators)) {
96 LIST_REMOVE(enumerators, n->enumerators, e);
101 LIST_REMOVE(siblings, n->parent->child, n);
103 assert_se(hashmap_remove(b->nodes, n->path) == n);
108 static void bus_reset_queues(sd_bus *b) {
113 for (i = 0; i < b->rqueue_size; i++)
114 sd_bus_message_unref(b->rqueue[i]);
117 for (i = 0; i < b->wqueue_size; i++)
118 sd_bus_message_unref(b->wqueue[i]);
121 b->rqueue = b->wqueue = NULL;
122 b->rqueue_allocated = b->wqueue_allocated = 0;
123 b->rqueue_size = b->wqueue_size = 0;
126 static void bus_free(sd_bus *b) {
127 struct filter_callback *f;
132 sd_bus_detach_event(b);
137 munmap(b->kdbus_buffer, KDBUS_POOL_SIZE);
140 free(b->unique_name);
141 free(b->auth_buffer);
146 free(b->cgroup_root);
147 free(b->connection_name);
150 strv_free(b->exec_argv);
152 close_many(b->fds, b->n_fds);
157 hashmap_free_free(b->reply_callbacks);
158 prioq_free(b->reply_callbacks_prioq);
160 while ((f = b->filter_callbacks)) {
161 LIST_REMOVE(callbacks, b->filter_callbacks, f);
165 bus_match_free(&b->match_callbacks);
167 hashmap_free_free(b->vtable_methods);
168 hashmap_free_free(b->vtable_properties);
170 while ((n = hashmap_first(b->nodes)))
171 bus_node_destroy(b, n);
173 hashmap_free(b->nodes);
175 bus_kernel_flush_memfd(b);
177 assert_se(pthread_mutex_destroy(&b->memfd_cache_mutex) == 0);
182 _public_ int sd_bus_new(sd_bus **ret) {
185 assert_return(ret, -EINVAL);
191 r->n_ref = REFCNT_INIT;
192 r->input_fd = r->output_fd = -1;
193 r->message_version = 1;
194 r->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
195 r->hello_flags |= KDBUS_HELLO_ACCEPT_FD;
196 r->attach_flags |= KDBUS_ATTACH_NAMES;
197 r->original_pid = getpid();
199 assert_se(pthread_mutex_init(&r->memfd_cache_mutex, NULL) == 0);
201 /* We guarantee that wqueue always has space for at least one
203 if (!GREEDY_REALLOC(r->wqueue, r->wqueue_allocated, 1)) {
212 _public_ int sd_bus_set_address(sd_bus *bus, const char *address) {
215 assert_return(bus, -EINVAL);
216 assert_return(bus->state == BUS_UNSET, -EPERM);
217 assert_return(address, -EINVAL);
218 assert_return(!bus_pid_changed(bus), -ECHILD);
230 _public_ int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd) {
231 assert_return(bus, -EINVAL);
232 assert_return(bus->state == BUS_UNSET, -EPERM);
233 assert_return(input_fd >= 0, -EINVAL);
234 assert_return(output_fd >= 0, -EINVAL);
235 assert_return(!bus_pid_changed(bus), -ECHILD);
237 bus->input_fd = input_fd;
238 bus->output_fd = output_fd;
242 _public_ int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]) {
245 assert_return(bus, -EINVAL);
246 assert_return(bus->state == BUS_UNSET, -EPERM);
247 assert_return(path, -EINVAL);
248 assert_return(!strv_isempty(argv), -EINVAL);
249 assert_return(!bus_pid_changed(bus), -ECHILD);
261 free(bus->exec_path);
262 strv_free(bus->exec_argv);
270 _public_ int sd_bus_set_bus_client(sd_bus *bus, int b) {
271 assert_return(bus, -EINVAL);
272 assert_return(bus->state == BUS_UNSET, -EPERM);
273 assert_return(!bus_pid_changed(bus), -ECHILD);
275 bus->bus_client = !!b;
279 _public_ int sd_bus_negotiate_fds(sd_bus *bus, int b) {
280 assert_return(bus, -EINVAL);
281 assert_return(bus->state == BUS_UNSET, -EPERM);
282 assert_return(!bus_pid_changed(bus), -ECHILD);
284 SET_FLAG(bus->hello_flags, KDBUS_HELLO_ACCEPT_FD, b);
288 _public_ int sd_bus_negotiate_timestamp(sd_bus *bus, int b) {
289 assert_return(bus, -EINVAL);
290 assert_return(bus->state == BUS_UNSET, -EPERM);
291 assert_return(!bus_pid_changed(bus), -ECHILD);
293 SET_FLAG(bus->attach_flags, KDBUS_ATTACH_TIMESTAMP, b);
297 _public_ int sd_bus_negotiate_creds(sd_bus *bus, uint64_t mask) {
298 assert_return(bus, -EINVAL);
299 assert_return(mask <= _SD_BUS_CREDS_ALL, -EINVAL);
300 assert_return(bus->state == BUS_UNSET, -EPERM);
301 assert_return(!bus_pid_changed(bus), -ECHILD);
303 /* The well knowns we need unconditionally, so that matches can work */
304 bus->creds_mask = mask | SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
306 return kdbus_translate_attach_flags(bus->creds_mask, &bus->creds_mask);
309 _public_ int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id) {
310 assert_return(bus, -EINVAL);
311 assert_return(b || sd_id128_equal(server_id, SD_ID128_NULL), -EINVAL);
312 assert_return(bus->state == BUS_UNSET, -EPERM);
313 assert_return(!bus_pid_changed(bus), -ECHILD);
315 bus->is_server = !!b;
316 bus->server_id = server_id;
320 _public_ int sd_bus_set_anonymous(sd_bus *bus, int b) {
321 assert_return(bus, -EINVAL);
322 assert_return(bus->state == BUS_UNSET, -EPERM);
323 assert_return(!bus_pid_changed(bus), -ECHILD);
325 bus->anonymous_auth = !!b;
329 _public_ int sd_bus_set_trusted(sd_bus *bus, int b) {
330 assert_return(bus, -EINVAL);
331 assert_return(bus->state == BUS_UNSET, -EPERM);
332 assert_return(!bus_pid_changed(bus), -ECHILD);
338 _public_ int sd_bus_set_name(sd_bus *bus, const char *name) {
341 assert_return(bus, -EINVAL);
342 assert_return(name, -EINVAL);
343 assert_return(bus->state == BUS_UNSET, -EPERM);
344 assert_return(!bus_pid_changed(bus), -ECHILD);
350 free(bus->connection_name);
351 bus->connection_name = n;
356 static int hello_callback(sd_bus *bus, sd_bus_message *reply, void *userdata, sd_bus_error *error) {
361 assert(bus->state == BUS_HELLO || bus->state == BUS_CLOSING);
364 r = sd_bus_message_get_errno(reply);
370 r = sd_bus_message_read(reply, "s", &s);
374 if (!service_name_is_valid(s) || s[0] != ':')
377 bus->unique_name = strdup(s);
378 if (!bus->unique_name)
381 if (bus->state == BUS_HELLO)
382 bus->state = BUS_RUNNING;
387 static int bus_send_hello(sd_bus *bus) {
388 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
393 if (!bus->bus_client || bus->is_kernel)
396 r = sd_bus_message_new_method_call(
398 "org.freedesktop.DBus",
399 "/org/freedesktop/DBus",
400 "org.freedesktop.DBus",
406 return sd_bus_call_async(bus, m, hello_callback, NULL, 0, &bus->hello_cookie);
409 int bus_start_running(sd_bus *bus) {
412 if (bus->bus_client && !bus->is_kernel) {
413 bus->state = BUS_HELLO;
417 bus->state = BUS_RUNNING;
421 static int parse_address_key(const char **p, const char *key, char **value) {
422 size_t l, n = 0, allocated = 0;
432 if (strncmp(*p, key, l) != 0)
445 while (*a != ';' && *a != ',' && *a != 0) {
463 c = (char) ((x << 4) | y);
470 if (!GREEDY_REALLOC(r, allocated, n + 2))
494 static void skip_address_key(const char **p) {
498 *p += strcspn(*p, ",");
504 static int parse_unix_address(sd_bus *b, const char **p, char **guid) {
505 _cleanup_free_ char *path = NULL, *abstract = NULL;
514 while (**p != 0 && **p != ';') {
515 r = parse_address_key(p, "guid", guid);
521 r = parse_address_key(p, "path", &path);
527 r = parse_address_key(p, "abstract", &abstract);
536 if (!path && !abstract)
539 if (path && abstract)
544 if (l > sizeof(b->sockaddr.un.sun_path))
547 b->sockaddr.un.sun_family = AF_UNIX;
548 strncpy(b->sockaddr.un.sun_path, path, sizeof(b->sockaddr.un.sun_path));
549 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l;
550 } else if (abstract) {
551 l = strlen(abstract);
552 if (l > sizeof(b->sockaddr.un.sun_path) - 1)
555 b->sockaddr.un.sun_family = AF_UNIX;
556 b->sockaddr.un.sun_path[0] = 0;
557 strncpy(b->sockaddr.un.sun_path+1, abstract, sizeof(b->sockaddr.un.sun_path)-1);
558 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
564 static int parse_tcp_address(sd_bus *b, const char **p, char **guid) {
565 _cleanup_free_ char *host = NULL, *port = NULL, *family = NULL;
567 struct addrinfo *result, hints = {
568 .ai_socktype = SOCK_STREAM,
569 .ai_flags = AI_ADDRCONFIG,
577 while (**p != 0 && **p != ';') {
578 r = parse_address_key(p, "guid", guid);
584 r = parse_address_key(p, "host", &host);
590 r = parse_address_key(p, "port", &port);
596 r = parse_address_key(p, "family", &family);
609 if (streq(family, "ipv4"))
610 hints.ai_family = AF_INET;
611 else if (streq(family, "ipv6"))
612 hints.ai_family = AF_INET6;
617 r = getaddrinfo(host, port, &hints, &result);
621 return -EADDRNOTAVAIL;
623 memcpy(&b->sockaddr, result->ai_addr, result->ai_addrlen);
624 b->sockaddr_size = result->ai_addrlen;
626 freeaddrinfo(result);
631 static int parse_exec_address(sd_bus *b, const char **p, char **guid) {
633 unsigned n_argv = 0, j;
635 size_t allocated = 0;
643 while (**p != 0 && **p != ';') {
644 r = parse_address_key(p, "guid", guid);
650 r = parse_address_key(p, "path", &path);
656 if (startswith(*p, "argv")) {
660 ul = strtoul(*p + 4, (char**) p, 10);
661 if (errno > 0 || **p != '=' || ul > 256) {
669 if (!GREEDY_REALLOC0(argv, allocated, ul + 2)) {
677 r = parse_address_key(p, NULL, argv + ul);
692 /* Make sure there are no holes in the array, with the
693 * exception of argv[0] */
694 for (j = 1; j < n_argv; j++)
700 if (argv && argv[0] == NULL) {
701 argv[0] = strdup(path);
713 for (j = 0; j < n_argv; j++)
721 static int parse_kernel_address(sd_bus *b, const char **p, char **guid) {
722 _cleanup_free_ char *path = NULL;
730 while (**p != 0 && **p != ';') {
731 r = parse_address_key(p, "guid", guid);
737 r = parse_address_key(p, "path", &path);
756 static int parse_container_unix_address(sd_bus *b, const char **p, char **guid) {
757 _cleanup_free_ char *machine = NULL;
765 while (**p != 0 && **p != ';') {
766 r = parse_address_key(p, "guid", guid);
772 r = parse_address_key(p, "machine", &machine);
784 if (!filename_is_safe(machine))
788 b->machine = machine;
791 b->sockaddr.un.sun_family = AF_UNIX;
792 strncpy(b->sockaddr.un.sun_path, "/var/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
793 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + sizeof("/var/run/dbus/system_bus_socket") - 1;
798 static int parse_container_kernel_address(sd_bus *b, const char **p, char **guid) {
799 _cleanup_free_ char *machine = NULL;
807 while (**p != 0 && **p != ';') {
808 r = parse_address_key(p, "guid", guid);
814 r = parse_address_key(p, "machine", &machine);
826 if (!filename_is_safe(machine))
830 b->machine = machine;
834 b->kernel = strdup("/dev/kdbus/0-system/bus");
841 static void bus_reset_parsed_address(sd_bus *b) {
845 b->sockaddr_size = 0;
846 strv_free(b->exec_argv);
850 b->server_id = SD_ID128_NULL;
857 static int bus_parse_next_address(sd_bus *b) {
858 _cleanup_free_ char *guid = NULL;
866 if (b->address[b->address_index] == 0)
869 bus_reset_parsed_address(b);
871 a = b->address + b->address_index;
880 if (startswith(a, "unix:")) {
883 r = parse_unix_address(b, &a, &guid);
888 } else if (startswith(a, "tcp:")) {
891 r = parse_tcp_address(b, &a, &guid);
897 } else if (startswith(a, "unixexec:")) {
900 r = parse_exec_address(b, &a, &guid);
906 } else if (startswith(a, "kernel:")) {
909 r = parse_kernel_address(b, &a, &guid);
914 } else if (startswith(a, "x-container-unix:")) {
917 r = parse_container_unix_address(b, &a, &guid);
922 } else if (startswith(a, "x-container-kernel:")) {
925 r = parse_container_kernel_address(b, &a, &guid);
938 r = sd_id128_from_string(guid, &b->server_id);
943 b->address_index = a - b->address;
947 static int bus_start_address(sd_bus *b) {
953 bool skipped = false;
958 r = bus_socket_exec(b);
959 else if (b->machine && b->kernel)
960 r = bus_container_connect_kernel(b);
961 else if (b->machine && b->sockaddr.sa.sa_family != AF_UNSPEC)
962 r = bus_container_connect_socket(b);
964 r = bus_kernel_connect(b);
965 else if (b->sockaddr.sa.sa_family != AF_UNSPEC)
966 r = bus_socket_connect(b);
972 r = attach_io_events(b);
977 b->last_connect_error = -r;
980 r = bus_parse_next_address(b);
984 return b->last_connect_error ? -b->last_connect_error : -ECONNREFUSED;
988 int bus_next_address(sd_bus *b) {
991 bus_reset_parsed_address(b);
992 return bus_start_address(b);
995 static int bus_start_fd(sd_bus *b) {
1000 assert(b->input_fd >= 0);
1001 assert(b->output_fd >= 0);
1003 r = fd_nonblock(b->input_fd, true);
1007 r = fd_cloexec(b->input_fd, true);
1011 if (b->input_fd != b->output_fd) {
1012 r = fd_nonblock(b->output_fd, true);
1016 r = fd_cloexec(b->output_fd, true);
1021 if (fstat(b->input_fd, &st) < 0)
1024 if (S_ISCHR(b->input_fd))
1025 return bus_kernel_take_fd(b);
1027 return bus_socket_take_fd(b);
1030 _public_ int sd_bus_start(sd_bus *bus) {
1033 assert_return(bus, -EINVAL);
1034 assert_return(bus->state == BUS_UNSET, -EPERM);
1035 assert_return(!bus_pid_changed(bus), -ECHILD);
1037 bus->state = BUS_OPENING;
1039 if (bus->is_server && bus->bus_client)
1042 if (bus->input_fd >= 0)
1043 r = bus_start_fd(bus);
1044 else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->kernel || bus->machine)
1045 r = bus_start_address(bus);
1052 return bus_send_hello(bus);
1055 _public_ int sd_bus_open_system(sd_bus **ret) {
1060 assert_return(ret, -EINVAL);
1066 e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1068 r = sd_bus_set_address(b, e);
1070 r = sd_bus_set_address(b, DEFAULT_SYSTEM_BUS_PATH);
1074 b->bus_client = true;
1075 b->is_system = true;
1077 /* Let's do per-method access control on the system bus. We
1078 * need the caller's UID and capability set for that. */
1080 b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1082 r = sd_bus_start(b);
1094 _public_ int sd_bus_open_user(sd_bus **ret) {
1099 assert_return(ret, -EINVAL);
1105 e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
1107 r = sd_bus_set_address(b, e);
1111 e = secure_getenv("XDG_RUNTIME_DIR");
1113 _cleanup_free_ char *ee = NULL;
1115 ee = bus_address_escape(e);
1122 asprintf(&b->address, KERNEL_USER_BUS_FMT ";" UNIX_USER_BUS_FMT, (unsigned long) getuid(), ee);
1124 asprintf(&b->address, UNIX_USER_BUS_FMT, ee);
1128 asprintf(&b->address, KERNEL_USER_BUS_FMT, (unsigned long) getuid());
1130 return -ECONNREFUSED;
1140 b->bus_client = true;
1143 /* We don't do any per-method access control on the user
1147 r = sd_bus_start(b);
1159 _public_ int sd_bus_open_system_remote(const char *host, sd_bus **ret) {
1160 _cleanup_free_ char *e = NULL;
1165 assert_return(host, -EINVAL);
1166 assert_return(ret, -EINVAL);
1168 e = bus_address_escape(host);
1172 p = strjoin("unixexec:path=ssh,argv1=-xT,argv2=", e, ",argv3=systemd-stdio-bridge", NULL);
1176 r = sd_bus_new(&bus);
1183 bus->bus_client = true;
1185 r = sd_bus_start(bus);
1195 _public_ int sd_bus_open_system_container(const char *machine, sd_bus **ret) {
1196 _cleanup_free_ char *e = NULL;
1201 assert_return(machine, -EINVAL);
1202 assert_return(ret, -EINVAL);
1203 assert_return(filename_is_safe(machine), -EINVAL);
1205 e = bus_address_escape(machine);
1210 p = strjoin("x-container-kernel:machine=", e, ";x-container-unix:machine=", e, NULL);
1212 p = strjoin("x-container-unix:machine=", e, NULL);
1217 r = sd_bus_new(&bus);
1224 bus->bus_client = true;
1226 r = sd_bus_start(bus);
1236 _public_ void sd_bus_close(sd_bus *bus) {
1240 if (bus->state == BUS_CLOSED)
1242 if (bus_pid_changed(bus))
1245 bus->state = BUS_CLOSED;
1247 sd_bus_detach_event(bus);
1249 /* Drop all queued messages so that they drop references to
1250 * the bus object and the bus may be freed */
1251 bus_reset_queues(bus);
1253 if (!bus->is_kernel)
1256 /* We'll leave the fd open in case this is a kernel bus, since
1257 * there might still be memblocks around that reference this
1258 * bus, and they might need to invoke the KDBUS_CMD_FREE
1259 * ioctl on the fd when they are freed. */
1262 static void bus_enter_closing(sd_bus *bus) {
1265 if (bus->state != BUS_OPENING &&
1266 bus->state != BUS_AUTHENTICATING &&
1267 bus->state != BUS_HELLO &&
1268 bus->state != BUS_RUNNING)
1271 bus->state = BUS_CLOSING;
1274 _public_ sd_bus *sd_bus_ref(sd_bus *bus) {
1275 assert_return(bus, NULL);
1277 assert_se(REFCNT_INC(bus->n_ref) >= 2);
1282 _public_ sd_bus *sd_bus_unref(sd_bus *bus) {
1288 i = REFCNT_DEC(bus->n_ref);
1289 if (i != bus->rqueue_size + bus->wqueue_size)
1292 for (i = 0; i < bus->rqueue_size; i++)
1293 if (bus->rqueue[i]->n_ref > 1)
1296 for (i = 0; i < bus->wqueue_size; i++)
1297 if (bus->wqueue[i]->n_ref > 1)
1300 /* we are the only holders on the messages */
1306 _public_ int sd_bus_is_open(sd_bus *bus) {
1308 assert_return(bus, -EINVAL);
1309 assert_return(!bus_pid_changed(bus), -ECHILD);
1311 return BUS_IS_OPEN(bus->state);
1314 _public_ int sd_bus_can_send(sd_bus *bus, char type) {
1317 assert_return(bus, -EINVAL);
1318 assert_return(bus->state != BUS_UNSET, -ENOTCONN);
1319 assert_return(!bus_pid_changed(bus), -ECHILD);
1321 if (type == SD_BUS_TYPE_UNIX_FD) {
1322 if (!(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD))
1325 r = bus_ensure_running(bus);
1329 return bus->can_fds;
1332 return bus_type_is_valid(type);
1335 _public_ int sd_bus_get_server_id(sd_bus *bus, sd_id128_t *server_id) {
1338 assert_return(bus, -EINVAL);
1339 assert_return(server_id, -EINVAL);
1340 assert_return(!bus_pid_changed(bus), -ECHILD);
1342 r = bus_ensure_running(bus);
1346 *server_id = bus->server_id;
1350 static int bus_seal_message(sd_bus *b, sd_bus_message *m, usec_t timeout) {
1355 /* If we copy the same message to multiple
1356 * destinations, avoid using the same cookie
1358 b->cookie = MAX(b->cookie, BUS_MESSAGE_COOKIE(m));
1363 timeout = BUS_DEFAULT_TIMEOUT;
1365 return bus_message_seal(m, ++b->cookie, timeout);
1368 static int bus_remarshal_message(sd_bus *b, sd_bus_message **m) {
1371 /* Do packet version and endianess already match? */
1372 if ((b->message_version == 0 || b->message_version == (*m)->header->version) &&
1373 (b->message_endian == 0 || b->message_endian == (*m)->header->endian))
1376 /* No? Then remarshal! */
1377 return bus_message_remarshal(b, m);
1380 int bus_seal_synthetic_message(sd_bus *b, sd_bus_message *m) {
1384 /* The bus specification says the serial number cannot be 0,
1385 * hence let's fill something in for synthetic messages. Since
1386 * synthetic messages might have a fake sender and we don't
1387 * want to interfere with the real sender's serial numbers we
1388 * pick a fixed, artifical one. We use (uint32_t) -1 rather
1389 * than (uint64_t) -1 since dbus1 only had 32bit identifiers,
1390 * even though kdbus can do 64bit. */
1392 return bus_message_seal(m, 0xFFFFFFFFULL, 0);
1395 static int bus_write_message(sd_bus *bus, sd_bus_message *m, bool hint_sync_call, size_t *idx) {
1402 r = bus_kernel_write_message(bus, m, hint_sync_call);
1404 r = bus_socket_write_message(bus, m, idx);
1409 if (bus->is_kernel || *idx >= BUS_MESSAGE_SIZE(m))
1410 log_debug("Sent message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%lu reply_cookie=%lu error=%s",
1411 bus_message_type_to_string(m->header->type),
1412 strna(sd_bus_message_get_sender(m)),
1413 strna(sd_bus_message_get_destination(m)),
1414 strna(sd_bus_message_get_path(m)),
1415 strna(sd_bus_message_get_interface(m)),
1416 strna(sd_bus_message_get_member(m)),
1417 (unsigned long) BUS_MESSAGE_COOKIE(m),
1418 (unsigned long) m->reply_cookie,
1419 strna(m->error.message));
1424 static int dispatch_wqueue(sd_bus *bus) {
1428 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1430 while (bus->wqueue_size > 0) {
1432 r = bus_write_message(bus, bus->wqueue[0], false, &bus->windex);
1436 /* Didn't do anything this time */
1438 else if (bus->is_kernel || bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
1439 /* Fully written. Let's drop the entry from
1442 * This isn't particularly optimized, but
1443 * well, this is supposed to be our worst-case
1444 * buffer only, and the socket buffer is
1445 * supposed to be our primary buffer, and if
1446 * it got full, then all bets are off
1449 bus->wqueue_size --;
1450 sd_bus_message_unref(bus->wqueue[0]);
1451 memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
1461 static int bus_read_message(sd_bus *bus) {
1465 return bus_kernel_read_message(bus);
1467 return bus_socket_read_message(bus);
1470 int bus_rqueue_make_room(sd_bus *bus) {
1473 if (bus->rqueue_size >= BUS_RQUEUE_MAX)
1476 if (!GREEDY_REALLOC(bus->rqueue, bus->rqueue_allocated, bus->rqueue_size + 1))
1482 static int dispatch_rqueue(sd_bus *bus, sd_bus_message **m) {
1487 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1490 if (bus->rqueue_size > 0) {
1491 /* Dispatch a queued message */
1493 *m = bus->rqueue[0];
1494 bus->rqueue_size --;
1495 memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
1499 /* Try to read a new message */
1500 r = bus_read_message(bus);
1510 static int bus_send_internal(sd_bus *bus, sd_bus_message *_m, uint64_t *cookie, bool hint_sync_call) {
1511 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1514 assert_return(bus, -EINVAL);
1515 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1516 assert_return(m, -EINVAL);
1517 assert_return(!bus_pid_changed(bus), -ECHILD);
1520 r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
1527 /* If the cookie number isn't kept, then we know that no reply
1529 if (!cookie && !m->sealed)
1530 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1532 r = bus_seal_message(bus, m, 0);
1536 /* Remarshall if we have to. This will possibly unref the
1537 * message and place a replacement in m */
1538 r = bus_remarshal_message(bus, &m);
1542 /* If this is a reply and no reply was requested, then let's
1543 * suppress this, if we can */
1544 if (m->dont_send && !cookie)
1547 if ((bus->state == BUS_RUNNING || bus->state == BUS_HELLO) && bus->wqueue_size <= 0) {
1550 r = bus_write_message(bus, m, hint_sync_call, &idx);
1552 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
1553 bus_enter_closing(bus);
1558 } else if (!bus->is_kernel && idx < BUS_MESSAGE_SIZE(m)) {
1559 /* Wasn't fully written. So let's remember how
1560 * much was written. Note that the first entry
1561 * of the wqueue array is always allocated so
1562 * that we always can remember how much was
1564 bus->wqueue[0] = sd_bus_message_ref(m);
1565 bus->wqueue_size = 1;
1569 /* Just append it to the queue. */
1571 if (bus->wqueue_size >= BUS_WQUEUE_MAX)
1574 if (!GREEDY_REALLOC(bus->wqueue, bus->wqueue_allocated, bus->wqueue_size + 1))
1577 bus->wqueue[bus->wqueue_size ++] = sd_bus_message_ref(m);
1581 *cookie = BUS_MESSAGE_COOKIE(m);
1586 _public_ int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *cookie) {
1587 return bus_send_internal(bus, m, cookie, false);
1590 _public_ int sd_bus_send_to(sd_bus *bus, sd_bus_message *m, const char *destination, uint64_t *cookie) {
1593 assert_return(bus, -EINVAL);
1594 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1595 assert_return(m, -EINVAL);
1596 assert_return(!bus_pid_changed(bus), -ECHILD);
1598 if (!streq_ptr(m->destination, destination)) {
1603 r = sd_bus_message_set_destination(m, destination);
1608 return sd_bus_send(bus, m, cookie);
1611 static usec_t calc_elapse(uint64_t usec) {
1612 if (usec == (uint64_t) -1)
1615 return now(CLOCK_MONOTONIC) + usec;
1618 static int timeout_compare(const void *a, const void *b) {
1619 const struct reply_callback *x = a, *y = b;
1621 if (x->timeout != 0 && y->timeout == 0)
1624 if (x->timeout == 0 && y->timeout != 0)
1627 if (x->timeout < y->timeout)
1630 if (x->timeout > y->timeout)
1636 _public_ int sd_bus_call_async(
1639 sd_bus_message_handler_t callback,
1644 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1645 struct reply_callback *c;
1648 assert_return(bus, -EINVAL);
1649 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1650 assert_return(m, -EINVAL);
1651 assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1652 assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1653 assert_return(callback, -EINVAL);
1654 assert_return(!bus_pid_changed(bus), -ECHILD);
1656 r = hashmap_ensure_allocated(&bus->reply_callbacks, uint64_hash_func, uint64_compare_func);
1660 r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
1664 r = bus_seal_message(bus, m, usec);
1668 r = bus_remarshal_message(bus, &m);
1672 c = new0(struct reply_callback, 1);
1676 c->callback = callback;
1677 c->userdata = userdata;
1678 c->cookie = BUS_MESSAGE_COOKIE(m);
1679 c->timeout = calc_elapse(m->timeout);
1681 r = hashmap_put(bus->reply_callbacks, &c->cookie, c);
1687 if (c->timeout != 0) {
1688 r = prioq_put(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1691 sd_bus_call_async_cancel(bus, c->cookie);
1696 r = sd_bus_send(bus, m, cookie);
1698 sd_bus_call_async_cancel(bus, c->cookie);
1705 _public_ int sd_bus_call_async_cancel(sd_bus *bus, uint64_t cookie) {
1706 struct reply_callback *c;
1708 assert_return(bus, -EINVAL);
1709 assert_return(cookie != 0, -EINVAL);
1710 assert_return(!bus_pid_changed(bus), -ECHILD);
1712 c = hashmap_remove(bus->reply_callbacks, &cookie);
1716 if (c->timeout != 0)
1717 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1723 int bus_ensure_running(sd_bus *bus) {
1728 if (bus->state == BUS_UNSET || bus->state == BUS_CLOSED || bus->state == BUS_CLOSING)
1730 if (bus->state == BUS_RUNNING)
1734 r = sd_bus_process(bus, NULL);
1737 if (bus->state == BUS_RUNNING)
1742 r = sd_bus_wait(bus, (uint64_t) -1);
1748 _public_ int sd_bus_call(
1752 sd_bus_error *error,
1753 sd_bus_message **reply) {
1755 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1761 assert_return(bus, -EINVAL);
1762 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1763 assert_return(m, -EINVAL);
1764 assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1765 assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1766 assert_return(!bus_error_is_dirty(error), -EINVAL);
1767 assert_return(!bus_pid_changed(bus), -ECHILD);
1769 r = bus_ensure_running(bus);
1773 i = bus->rqueue_size;
1775 r = bus_seal_message(bus, m, usec);
1779 r = bus_remarshal_message(bus, &m);
1783 r = bus_send_internal(bus, m, &cookie, true);
1787 timeout = calc_elapse(m->timeout);
1792 while (i < bus->rqueue_size) {
1793 sd_bus_message *incoming = NULL;
1795 incoming = bus->rqueue[i];
1797 if (incoming->reply_cookie == cookie) {
1798 /* Found a match! */
1800 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1803 if (incoming->header->type == SD_BUS_MESSAGE_METHOD_RETURN) {
1808 sd_bus_message_unref(incoming);
1811 } else if (incoming->header->type == SD_BUS_MESSAGE_METHOD_ERROR)
1812 r = sd_bus_error_copy(error, &incoming->error);
1816 sd_bus_message_unref(incoming);
1819 } else if (BUS_MESSAGE_COOKIE(incoming) == cookie &&
1822 streq(bus->unique_name, incoming->sender)) {
1824 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1827 /* Our own message? Somebody is trying
1828 * to send its own client a message,
1829 * let's not dead-lock, let's fail
1832 sd_bus_message_unref(incoming);
1836 /* Try to read more, right-away */
1840 r = bus_read_message(bus);
1842 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
1843 bus_enter_closing(bus);
1855 n = now(CLOCK_MONOTONIC);
1861 left = (uint64_t) -1;
1863 r = bus_poll(bus, true, left);
1869 r = dispatch_wqueue(bus);
1871 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
1872 bus_enter_closing(bus);
1881 _public_ int sd_bus_get_fd(sd_bus *bus) {
1883 assert_return(bus, -EINVAL);
1884 assert_return(bus->input_fd == bus->output_fd, -EPERM);
1885 assert_return(!bus_pid_changed(bus), -ECHILD);
1887 return bus->input_fd;
1890 _public_ int sd_bus_get_events(sd_bus *bus) {
1893 assert_return(bus, -EINVAL);
1894 assert_return(BUS_IS_OPEN(bus->state) || bus->state == BUS_CLOSING, -ENOTCONN);
1895 assert_return(!bus_pid_changed(bus), -ECHILD);
1897 if (bus->state == BUS_OPENING)
1899 else if (bus->state == BUS_AUTHENTICATING) {
1901 if (bus_socket_auth_needs_write(bus))
1906 } else if (bus->state == BUS_RUNNING || bus->state == BUS_HELLO) {
1907 if (bus->rqueue_size <= 0)
1909 if (bus->wqueue_size > 0)
1916 _public_ int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
1917 struct reply_callback *c;
1919 assert_return(bus, -EINVAL);
1920 assert_return(timeout_usec, -EINVAL);
1921 assert_return(BUS_IS_OPEN(bus->state) || bus->state == BUS_CLOSING, -ENOTCONN);
1922 assert_return(!bus_pid_changed(bus), -ECHILD);
1924 if (bus->state == BUS_CLOSING) {
1929 if (bus->state == BUS_AUTHENTICATING) {
1930 *timeout_usec = bus->auth_timeout;
1934 if (bus->state != BUS_RUNNING && bus->state != BUS_HELLO) {
1935 *timeout_usec = (uint64_t) -1;
1939 if (bus->rqueue_size > 0) {
1944 c = prioq_peek(bus->reply_callbacks_prioq);
1946 *timeout_usec = (uint64_t) -1;
1950 *timeout_usec = c->timeout;
1954 static int process_timeout(sd_bus *bus) {
1955 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
1956 _cleanup_bus_message_unref_ sd_bus_message* m = NULL;
1957 struct reply_callback *c;
1963 c = prioq_peek(bus->reply_callbacks_prioq);
1967 n = now(CLOCK_MONOTONIC);
1971 r = bus_message_new_synthetic_error(
1974 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
1979 m->sender = "org.freedesktop.DBus";
1981 r = bus_seal_synthetic_message(bus, m);
1985 assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
1986 hashmap_remove(bus->reply_callbacks, &c->cookie);
1989 bus->iteration_counter ++;
1991 r = c->callback(bus, m, c->userdata, &error_buffer);
1992 r = bus_maybe_reply_error(m, r, &error_buffer);
1995 bus->current = NULL;
2000 static int process_hello(sd_bus *bus, sd_bus_message *m) {
2004 if (bus->state != BUS_HELLO)
2007 /* Let's make sure the first message on the bus is the HELLO
2008 * reply. But note that we don't actually parse the message
2009 * here (we leave that to the usual handling), we just verify
2010 * we don't let any earlier msg through. */
2012 if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2013 m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2016 if (m->reply_cookie != bus->hello_cookie)
2022 static int process_reply(sd_bus *bus, sd_bus_message *m) {
2023 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2024 struct reply_callback *c;
2030 if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2031 m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2034 c = hashmap_remove(bus->reply_callbacks, &m->reply_cookie);
2038 if (c->timeout != 0)
2039 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2041 r = sd_bus_message_rewind(m, true);
2045 r = c->callback(bus, m, c->userdata, &error_buffer);
2046 r = bus_maybe_reply_error(m, r, &error_buffer);
2052 static int process_filter(sd_bus *bus, sd_bus_message *m) {
2053 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2054 struct filter_callback *l;
2061 bus->filter_callbacks_modified = false;
2063 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
2065 if (bus->filter_callbacks_modified)
2068 /* Don't run this more than once per iteration */
2069 if (l->last_iteration == bus->iteration_counter)
2072 l->last_iteration = bus->iteration_counter;
2074 r = sd_bus_message_rewind(m, true);
2078 r = l->callback(bus, m, l->userdata, &error_buffer);
2079 r = bus_maybe_reply_error(m, r, &error_buffer);
2085 } while (bus->filter_callbacks_modified);
2090 static int process_match(sd_bus *bus, sd_bus_message *m) {
2097 bus->match_callbacks_modified = false;
2099 r = bus_match_run(bus, &bus->match_callbacks, m);
2103 } while (bus->match_callbacks_modified);
2108 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
2109 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2115 if (bus->manual_peer_interface)
2118 if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2121 if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2124 if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2127 if (streq_ptr(m->member, "Ping"))
2128 r = sd_bus_message_new_method_return(m, &reply);
2129 else if (streq_ptr(m->member, "GetMachineId")) {
2133 r = sd_id128_get_machine(&id);
2137 r = sd_bus_message_new_method_return(m, &reply);
2141 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2143 r = sd_bus_message_new_method_errorf(
2145 SD_BUS_ERROR_UNKNOWN_METHOD,
2146 "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2152 r = sd_bus_send(bus, reply, NULL);
2159 static int process_message(sd_bus *bus, sd_bus_message *m) {
2166 bus->iteration_counter++;
2168 log_debug("Got message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%lu reply_cookie=%lu error=%s",
2169 bus_message_type_to_string(m->header->type),
2170 strna(sd_bus_message_get_sender(m)),
2171 strna(sd_bus_message_get_destination(m)),
2172 strna(sd_bus_message_get_path(m)),
2173 strna(sd_bus_message_get_interface(m)),
2174 strna(sd_bus_message_get_member(m)),
2175 (unsigned long) BUS_MESSAGE_COOKIE(m),
2176 (unsigned long) m->reply_cookie,
2177 strna(m->error.message));
2179 r = process_hello(bus, m);
2183 r = process_reply(bus, m);
2187 r = process_filter(bus, m);
2191 r = process_match(bus, m);
2195 r = process_builtin(bus, m);
2199 r = bus_process_object(bus, m);
2202 bus->current = NULL;
2206 static int process_running(sd_bus *bus, sd_bus_message **ret) {
2207 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2211 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
2213 r = process_timeout(bus);
2217 r = dispatch_wqueue(bus);
2221 r = dispatch_rqueue(bus, &m);
2227 r = process_message(bus, m);
2232 r = sd_bus_message_rewind(m, true);
2241 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2243 log_debug("Unprocessed message call sender=%s object=%s interface=%s member=%s",
2244 strna(sd_bus_message_get_sender(m)),
2245 strna(sd_bus_message_get_path(m)),
2246 strna(sd_bus_message_get_interface(m)),
2247 strna(sd_bus_message_get_member(m)));
2249 r = sd_bus_reply_method_errorf(
2251 SD_BUS_ERROR_UNKNOWN_OBJECT,
2252 "Unknown object '%s'.", m->path);
2266 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2267 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2268 struct reply_callback *c;
2272 assert(bus->state == BUS_CLOSING);
2274 c = hashmap_first(bus->reply_callbacks);
2276 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2278 /* First, fail all outstanding method calls */
2279 r = bus_message_new_synthetic_error(
2282 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2287 r = bus_seal_synthetic_message(bus, m);
2291 if (c->timeout != 0)
2292 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2294 hashmap_remove(bus->reply_callbacks, &c->cookie);
2297 bus->iteration_counter++;
2299 r = c->callback(bus, m, c->userdata, &error_buffer);
2300 r = bus_maybe_reply_error(m, r, &error_buffer);
2306 /* Then, synthesize a Disconnected message */
2307 r = sd_bus_message_new_signal(
2309 "/org/freedesktop/DBus/Local",
2310 "org.freedesktop.DBus.Local",
2316 m->sender = "org.freedesktop.DBus.Local";
2318 r = bus_seal_synthetic_message(bus, m);
2325 bus->iteration_counter++;
2327 r = process_filter(bus, m);
2331 r = process_match(bus, m);
2343 bus->current = NULL;
2347 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2348 BUS_DONT_DESTROY(bus);
2351 /* Returns 0 when we didn't do anything. This should cause the
2352 * caller to invoke sd_bus_wait() before returning the next
2353 * time. Returns > 0 when we did something, which possibly
2354 * means *ret is filled in with an unprocessed message. */
2356 assert_return(bus, -EINVAL);
2357 assert_return(!bus_pid_changed(bus), -ECHILD);
2359 /* We don't allow recursively invoking sd_bus_process(). */
2360 assert_return(!bus->current, -EBUSY);
2362 switch (bus->state) {
2371 r = bus_socket_process_opening(bus);
2372 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2373 bus_enter_closing(bus);
2381 case BUS_AUTHENTICATING:
2382 r = bus_socket_process_authenticating(bus);
2383 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2384 bus_enter_closing(bus);
2396 r = process_running(bus, ret);
2397 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2398 bus_enter_closing(bus);
2408 return process_closing(bus, ret);
2411 assert_not_reached("Unknown state");
2414 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2415 struct pollfd p[2] = {};
2418 usec_t m = (usec_t) -1;
2422 if (bus->state == BUS_CLOSING)
2425 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2427 e = sd_bus_get_events(bus);
2432 /* The caller really needs some more data, he doesn't
2433 * care about what's already read, or any timeouts
2438 /* The caller wants to process if there's something to
2439 * process, but doesn't care otherwise */
2441 r = sd_bus_get_timeout(bus, &until);
2446 nw = now(CLOCK_MONOTONIC);
2447 m = until > nw ? until - nw : 0;
2451 if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
2454 p[0].fd = bus->input_fd;
2455 if (bus->output_fd == bus->input_fd) {
2459 p[0].events = e & POLLIN;
2460 p[1].fd = bus->output_fd;
2461 p[1].events = e & POLLOUT;
2465 r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
2469 return r > 0 ? 1 : 0;
2472 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
2474 assert_return(bus, -EINVAL);
2475 assert_return(!bus_pid_changed(bus), -ECHILD);
2477 if (bus->state == BUS_CLOSING)
2480 assert_return(BUS_IS_OPEN(bus->state) , -ENOTCONN);
2482 if (bus->rqueue_size > 0)
2485 return bus_poll(bus, false, timeout_usec);
2488 _public_ int sd_bus_flush(sd_bus *bus) {
2491 assert_return(bus, -EINVAL);
2492 assert_return(!bus_pid_changed(bus), -ECHILD);
2494 if (bus->state == BUS_CLOSING)
2497 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2499 r = bus_ensure_running(bus);
2503 if (bus->wqueue_size <= 0)
2507 r = dispatch_wqueue(bus);
2509 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2510 bus_enter_closing(bus);
2517 if (bus->wqueue_size <= 0)
2520 r = bus_poll(bus, false, (uint64_t) -1);
2526 _public_ int sd_bus_add_filter(sd_bus *bus,
2527 sd_bus_message_handler_t callback,
2530 struct filter_callback *f;
2532 assert_return(bus, -EINVAL);
2533 assert_return(callback, -EINVAL);
2534 assert_return(!bus_pid_changed(bus), -ECHILD);
2536 f = new0(struct filter_callback, 1);
2539 f->callback = callback;
2540 f->userdata = userdata;
2542 bus->filter_callbacks_modified = true;
2543 LIST_PREPEND(callbacks, bus->filter_callbacks, f);
2547 _public_ int sd_bus_remove_filter(sd_bus *bus,
2548 sd_bus_message_handler_t callback,
2551 struct filter_callback *f;
2553 assert_return(bus, -EINVAL);
2554 assert_return(callback, -EINVAL);
2555 assert_return(!bus_pid_changed(bus), -ECHILD);
2557 LIST_FOREACH(callbacks, f, bus->filter_callbacks) {
2558 if (f->callback == callback && f->userdata == userdata) {
2559 bus->filter_callbacks_modified = true;
2560 LIST_REMOVE(callbacks, bus->filter_callbacks, f);
2569 _public_ int sd_bus_add_match(sd_bus *bus,
2571 sd_bus_message_handler_t callback,
2574 struct bus_match_component *components = NULL;
2575 unsigned n_components = 0;
2576 uint64_t cookie = 0;
2579 assert_return(bus, -EINVAL);
2580 assert_return(match, -EINVAL);
2581 assert_return(!bus_pid_changed(bus), -ECHILD);
2583 r = bus_match_parse(match, &components, &n_components);
2587 if (bus->bus_client) {
2588 cookie = ++bus->match_cookie;
2590 r = bus_add_match_internal(bus, match, components, n_components, cookie);
2595 bus->match_callbacks_modified = true;
2596 r = bus_match_add(&bus->match_callbacks, components, n_components, callback, userdata, cookie, NULL);
2598 if (bus->bus_client)
2599 bus_remove_match_internal(bus, match, cookie);
2603 bus_match_parse_free(components, n_components);
2607 _public_ int sd_bus_remove_match(sd_bus *bus,
2609 sd_bus_message_handler_t callback,
2612 struct bus_match_component *components = NULL;
2613 unsigned n_components = 0;
2615 uint64_t cookie = 0;
2617 assert_return(bus, -EINVAL);
2618 assert_return(match, -EINVAL);
2619 assert_return(!bus_pid_changed(bus), -ECHILD);
2621 r = bus_match_parse(match, &components, &n_components);
2625 bus->match_callbacks_modified = true;
2626 r = bus_match_remove(&bus->match_callbacks, components, n_components, callback, userdata, &cookie);
2628 if (bus->bus_client)
2629 q = bus_remove_match_internal(bus, match, cookie);
2631 bus_match_parse_free(components, n_components);
2633 return r < 0 ? r : q;
2636 bool bus_pid_changed(sd_bus *bus) {
2639 /* We don't support people creating a bus connection and
2640 * keeping it around over a fork(). Let's complain. */
2642 return bus->original_pid != getpid();
2645 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2646 sd_bus *bus = userdata;
2651 r = sd_bus_process(bus, NULL);
2658 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
2659 sd_bus *bus = userdata;
2664 r = sd_bus_process(bus, NULL);
2671 static int prepare_callback(sd_event_source *s, void *userdata) {
2672 sd_bus *bus = userdata;
2679 e = sd_bus_get_events(bus);
2683 if (bus->output_fd != bus->input_fd) {
2685 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
2689 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
2693 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
2698 r = sd_bus_get_timeout(bus, &until);
2704 j = sd_event_source_set_time(bus->time_event_source, until);
2709 r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
2716 static int quit_callback(sd_event_source *event, void *userdata) {
2717 sd_bus *bus = userdata;
2726 static int attach_io_events(sd_bus *bus) {
2731 if (bus->input_fd < 0)
2737 if (!bus->input_io_event_source) {
2738 r = sd_event_add_io(bus->event, bus->input_fd, 0, io_callback, bus, &bus->input_io_event_source);
2742 r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
2746 r = sd_event_source_set_priority(bus->input_io_event_source, bus->event_priority);
2748 r = sd_event_source_set_io_fd(bus->input_io_event_source, bus->input_fd);
2753 if (bus->output_fd != bus->input_fd) {
2754 assert(bus->output_fd >= 0);
2756 if (!bus->output_io_event_source) {
2757 r = sd_event_add_io(bus->event, bus->output_fd, 0, io_callback, bus, &bus->output_io_event_source);
2761 r = sd_event_source_set_priority(bus->output_io_event_source, bus->event_priority);
2763 r = sd_event_source_set_io_fd(bus->output_io_event_source, bus->output_fd);
2772 static void detach_io_events(sd_bus *bus) {
2775 if (bus->input_io_event_source) {
2776 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
2777 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
2780 if (bus->output_io_event_source) {
2781 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
2782 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
2786 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
2789 assert_return(bus, -EINVAL);
2790 assert_return(!bus->event, -EBUSY);
2792 assert(!bus->input_io_event_source);
2793 assert(!bus->output_io_event_source);
2794 assert(!bus->time_event_source);
2797 bus->event = sd_event_ref(event);
2799 r = sd_event_default(&bus->event);
2804 bus->event_priority = priority;
2806 r = sd_event_add_monotonic(bus->event, 0, 0, time_callback, bus, &bus->time_event_source);
2810 r = sd_event_source_set_priority(bus->time_event_source, priority);
2814 r = sd_event_add_exit(bus->event, quit_callback, bus, &bus->quit_event_source);
2818 r = attach_io_events(bus);
2825 sd_bus_detach_event(bus);
2829 _public_ int sd_bus_detach_event(sd_bus *bus) {
2830 assert_return(bus, -EINVAL);
2835 detach_io_events(bus);
2837 if (bus->time_event_source) {
2838 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
2839 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
2842 if (bus->quit_event_source) {
2843 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
2844 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
2848 bus->event = sd_event_unref(bus->event);
2853 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
2854 assert_return(bus, NULL);
2859 _public_ sd_bus_message* sd_bus_get_current(sd_bus *bus) {
2860 assert_return(bus, NULL);
2862 return bus->current;
2865 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
2870 assert(default_bus);
2873 return !!*default_bus;
2876 *ret = sd_bus_ref(*default_bus);
2884 b->default_bus_ptr = default_bus;
2892 _public_ int sd_bus_default_system(sd_bus **ret) {
2893 static thread_local sd_bus *default_system_bus = NULL;
2895 return bus_default(sd_bus_open_system, &default_system_bus, ret);
2898 _public_ int sd_bus_default_user(sd_bus **ret) {
2899 static thread_local sd_bus *default_user_bus = NULL;
2901 return bus_default(sd_bus_open_user, &default_user_bus, ret);
2904 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
2905 assert_return(b, -EINVAL);
2906 assert_return(tid, -EINVAL);
2907 assert_return(!bus_pid_changed(b), -ECHILD);
2915 return sd_event_get_tid(b->event, tid);
2920 _public_ char *sd_bus_label_escape(const char *s) {
2924 assert_return(s, NULL);
2926 /* Escapes all chars that D-Bus' object path cannot deal
2927 * with. Can be reversed with bus_path_unescape(). We special
2928 * case the empty string. */
2933 r = new(char, strlen(s)*3 + 1);
2937 for (f = s, t = r; *f; f++) {
2939 /* Escape everything that is not a-zA-Z0-9. We also
2940 * escape 0-9 if it's the first character */
2942 if (!(*f >= 'A' && *f <= 'Z') &&
2943 !(*f >= 'a' && *f <= 'z') &&
2944 !(f > s && *f >= '0' && *f <= '9')) {
2946 *(t++) = hexchar(*f >> 4);
2947 *(t++) = hexchar(*f);
2957 _public_ char *sd_bus_label_unescape(const char *f) {
2960 assert_return(f, NULL);
2962 /* Special case for the empty string */
2966 r = new(char, strlen(f) + 1);
2970 for (t = r; *f; f++) {
2975 if ((a = unhexchar(f[1])) < 0 ||
2976 (b = unhexchar(f[2])) < 0) {
2977 /* Invalid escape code, let's take it literal then */
2980 *(t++) = (char) ((a << 4) | b);
2992 _public_ int sd_bus_get_peer_creds(sd_bus *bus, uint64_t mask, sd_bus_creds **ret) {
2997 assert_return(bus, -EINVAL);
2998 assert_return(mask <= _SD_BUS_CREDS_ALL, -ENOTSUP);
2999 assert_return(ret, -EINVAL);
3000 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
3001 assert_return(!bus_pid_changed(bus), -ECHILD);
3002 assert_return(!bus->is_kernel, -ENOTSUP);
3004 if (!bus->ucred_valid && !isempty(bus->label))
3007 c = bus_creds_new();
3011 if (bus->ucred_valid) {
3012 pid = c->pid = bus->ucred.pid;
3013 c->uid = bus->ucred.uid;
3014 c->gid = bus->ucred.gid;
3016 c->mask |= (SD_BUS_CREDS_UID | SD_BUS_CREDS_PID | SD_BUS_CREDS_GID) & mask;
3019 if (!isempty(bus->label) && (mask & SD_BUS_CREDS_SELINUX_CONTEXT)) {
3020 c->label = strdup(bus->label);
3022 sd_bus_creds_unref(c);
3026 c->mask |= SD_BUS_CREDS_SELINUX_CONTEXT;
3029 r = bus_creds_add_more(c, mask, pid, 0);
3037 _public_ int sd_bus_try_close(sd_bus *bus) {
3040 assert_return(bus, -EINVAL);
3041 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
3042 assert_return(!bus_pid_changed(bus), -ECHILD);
3043 assert_return(bus->is_kernel, -ENOTSUP);
3045 if (bus->rqueue_size > 0)
3048 if (bus->wqueue_size > 0)
3051 r = bus_kernel_try_close(bus);
3059 _public_ int sd_bus_get_name(sd_bus *bus, const char **name) {
3060 assert_return(bus, -EINVAL);
3061 assert_return(name, -EINVAL);
3062 assert_return(!bus_pid_changed(bus), -ECHILD);
3064 *name = bus->connection_name;