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);
149 strv_free(b->exec_argv);
151 close_many(b->fds, b->n_fds);
156 hashmap_free_free(b->reply_callbacks);
157 prioq_free(b->reply_callbacks_prioq);
159 while ((f = b->filter_callbacks)) {
160 LIST_REMOVE(callbacks, b->filter_callbacks, f);
164 bus_match_free(&b->match_callbacks);
166 hashmap_free_free(b->vtable_methods);
167 hashmap_free_free(b->vtable_properties);
169 while ((n = hashmap_first(b->nodes)))
170 bus_node_destroy(b, n);
172 hashmap_free(b->nodes);
174 bus_kernel_flush_memfd(b);
176 assert_se(pthread_mutex_destroy(&b->memfd_cache_mutex) == 0);
181 _public_ int sd_bus_new(sd_bus **ret) {
184 assert_return(ret, -EINVAL);
190 r->n_ref = REFCNT_INIT;
191 r->input_fd = r->output_fd = -1;
192 r->message_version = 1;
193 r->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
194 r->hello_flags |= KDBUS_HELLO_ACCEPT_FD;
195 r->attach_flags |= KDBUS_ATTACH_NAMES;
196 r->original_pid = getpid();
198 assert_se(pthread_mutex_init(&r->memfd_cache_mutex, NULL) == 0);
200 /* We guarantee that wqueue always has space for at least one
202 if (!GREEDY_REALLOC(r->wqueue, r->wqueue_allocated, 1)) {
211 _public_ int sd_bus_set_address(sd_bus *bus, const char *address) {
214 assert_return(bus, -EINVAL);
215 assert_return(bus->state == BUS_UNSET, -EPERM);
216 assert_return(address, -EINVAL);
217 assert_return(!bus_pid_changed(bus), -ECHILD);
229 _public_ int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd) {
230 assert_return(bus, -EINVAL);
231 assert_return(bus->state == BUS_UNSET, -EPERM);
232 assert_return(input_fd >= 0, -EINVAL);
233 assert_return(output_fd >= 0, -EINVAL);
234 assert_return(!bus_pid_changed(bus), -ECHILD);
236 bus->input_fd = input_fd;
237 bus->output_fd = output_fd;
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_negotiate_fds(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_ACCEPT_FD, b);
287 _public_ int sd_bus_negotiate_attach_timestamp(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->attach_flags, KDBUS_ATTACH_TIMESTAMP, b);
296 _public_ int sd_bus_negotiate_attach_creds(sd_bus *bus, uint64_t mask) {
297 assert_return(bus, -EINVAL);
298 assert_return(mask <= _SD_BUS_CREDS_ALL, -EINVAL);
299 assert_return(bus->state == BUS_UNSET, -EPERM);
300 assert_return(!bus_pid_changed(bus), -ECHILD);
302 /* The well knowns we need unconditionally, so that matches can work */
303 bus->creds_mask = mask | SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
305 return kdbus_translate_attach_flags(bus->creds_mask, &bus->creds_mask);
308 _public_ int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id) {
309 assert_return(bus, -EINVAL);
310 assert_return(b || sd_id128_equal(server_id, SD_ID128_NULL), -EINVAL);
311 assert_return(bus->state == BUS_UNSET, -EPERM);
312 assert_return(!bus_pid_changed(bus), -ECHILD);
314 bus->is_server = !!b;
315 bus->server_id = server_id;
319 _public_ int sd_bus_set_anonymous(sd_bus *bus, int b) {
320 assert_return(bus, -EINVAL);
321 assert_return(bus->state == BUS_UNSET, -EPERM);
322 assert_return(!bus_pid_changed(bus), -ECHILD);
324 bus->anonymous_auth = !!b;
328 _public_ int sd_bus_set_trusted(sd_bus *bus, int b) {
329 assert_return(bus, -EINVAL);
330 assert_return(bus->state == BUS_UNSET, -EPERM);
331 assert_return(!bus_pid_changed(bus), -ECHILD);
337 static int hello_callback(sd_bus *bus, sd_bus_message *reply, void *userdata, sd_bus_error *error) {
342 assert(bus->state == BUS_HELLO || bus->state == BUS_CLOSING);
345 r = sd_bus_message_get_errno(reply);
351 r = sd_bus_message_read(reply, "s", &s);
355 if (!service_name_is_valid(s) || s[0] != ':')
358 bus->unique_name = strdup(s);
359 if (!bus->unique_name)
362 if (bus->state == BUS_HELLO)
363 bus->state = BUS_RUNNING;
368 static int bus_send_hello(sd_bus *bus) {
369 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
374 if (!bus->bus_client || bus->is_kernel)
377 r = sd_bus_message_new_method_call(
379 "org.freedesktop.DBus",
380 "/org/freedesktop/DBus",
381 "org.freedesktop.DBus",
387 return sd_bus_call_async(bus, m, hello_callback, NULL, 0, &bus->hello_cookie);
390 int bus_start_running(sd_bus *bus) {
393 if (bus->bus_client && !bus->is_kernel) {
394 bus->state = BUS_HELLO;
398 bus->state = BUS_RUNNING;
402 static int parse_address_key(const char **p, const char *key, char **value) {
403 size_t l, n = 0, allocated = 0;
413 if (strncmp(*p, key, l) != 0)
426 while (*a != ';' && *a != ',' && *a != 0) {
444 c = (char) ((x << 4) | y);
451 if (!GREEDY_REALLOC(r, allocated, n + 2))
475 static void skip_address_key(const char **p) {
479 *p += strcspn(*p, ",");
485 static int parse_unix_address(sd_bus *b, const char **p, char **guid) {
486 _cleanup_free_ char *path = NULL, *abstract = NULL;
495 while (**p != 0 && **p != ';') {
496 r = parse_address_key(p, "guid", guid);
502 r = parse_address_key(p, "path", &path);
508 r = parse_address_key(p, "abstract", &abstract);
517 if (!path && !abstract)
520 if (path && abstract)
525 if (l > sizeof(b->sockaddr.un.sun_path))
528 b->sockaddr.un.sun_family = AF_UNIX;
529 strncpy(b->sockaddr.un.sun_path, path, sizeof(b->sockaddr.un.sun_path));
530 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l;
531 } else if (abstract) {
532 l = strlen(abstract);
533 if (l > sizeof(b->sockaddr.un.sun_path) - 1)
536 b->sockaddr.un.sun_family = AF_UNIX;
537 b->sockaddr.un.sun_path[0] = 0;
538 strncpy(b->sockaddr.un.sun_path+1, abstract, sizeof(b->sockaddr.un.sun_path)-1);
539 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
545 static int parse_tcp_address(sd_bus *b, const char **p, char **guid) {
546 _cleanup_free_ char *host = NULL, *port = NULL, *family = NULL;
548 struct addrinfo *result, hints = {
549 .ai_socktype = SOCK_STREAM,
550 .ai_flags = AI_ADDRCONFIG,
558 while (**p != 0 && **p != ';') {
559 r = parse_address_key(p, "guid", guid);
565 r = parse_address_key(p, "host", &host);
571 r = parse_address_key(p, "port", &port);
577 r = parse_address_key(p, "family", &family);
590 if (streq(family, "ipv4"))
591 hints.ai_family = AF_INET;
592 else if (streq(family, "ipv6"))
593 hints.ai_family = AF_INET6;
598 r = getaddrinfo(host, port, &hints, &result);
602 return -EADDRNOTAVAIL;
604 memcpy(&b->sockaddr, result->ai_addr, result->ai_addrlen);
605 b->sockaddr_size = result->ai_addrlen;
607 freeaddrinfo(result);
612 static int parse_exec_address(sd_bus *b, const char **p, char **guid) {
614 unsigned n_argv = 0, j;
616 size_t allocated = 0;
624 while (**p != 0 && **p != ';') {
625 r = parse_address_key(p, "guid", guid);
631 r = parse_address_key(p, "path", &path);
637 if (startswith(*p, "argv")) {
641 ul = strtoul(*p + 4, (char**) p, 10);
642 if (errno > 0 || **p != '=' || ul > 256) {
650 if (!GREEDY_REALLOC0(argv, allocated, ul + 2)) {
658 r = parse_address_key(p, NULL, argv + ul);
673 /* Make sure there are no holes in the array, with the
674 * exception of argv[0] */
675 for (j = 1; j < n_argv; j++)
681 if (argv && argv[0] == NULL) {
682 argv[0] = strdup(path);
694 for (j = 0; j < n_argv; j++)
702 static int parse_kernel_address(sd_bus *b, const char **p, char **guid) {
703 _cleanup_free_ char *path = NULL;
711 while (**p != 0 && **p != ';') {
712 r = parse_address_key(p, "guid", guid);
718 r = parse_address_key(p, "path", &path);
737 static int parse_container_unix_address(sd_bus *b, const char **p, char **guid) {
738 _cleanup_free_ char *machine = NULL;
746 while (**p != 0 && **p != ';') {
747 r = parse_address_key(p, "guid", guid);
753 r = parse_address_key(p, "machine", &machine);
765 if (!filename_is_safe(machine))
769 b->machine = machine;
772 b->sockaddr.un.sun_family = AF_UNIX;
773 strncpy(b->sockaddr.un.sun_path, "/var/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
774 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + sizeof("/var/run/dbus/system_bus_socket") - 1;
779 static int parse_container_kernel_address(sd_bus *b, const char **p, char **guid) {
780 _cleanup_free_ char *machine = NULL;
788 while (**p != 0 && **p != ';') {
789 r = parse_address_key(p, "guid", guid);
795 r = parse_address_key(p, "machine", &machine);
807 if (!filename_is_safe(machine))
811 b->machine = machine;
815 b->kernel = strdup("/dev/kdbus/0-system/bus");
822 static void bus_reset_parsed_address(sd_bus *b) {
826 b->sockaddr_size = 0;
827 strv_free(b->exec_argv);
831 b->server_id = SD_ID128_NULL;
838 static int bus_parse_next_address(sd_bus *b) {
839 _cleanup_free_ char *guid = NULL;
847 if (b->address[b->address_index] == 0)
850 bus_reset_parsed_address(b);
852 a = b->address + b->address_index;
861 if (startswith(a, "unix:")) {
864 r = parse_unix_address(b, &a, &guid);
869 } else if (startswith(a, "tcp:")) {
872 r = parse_tcp_address(b, &a, &guid);
878 } else if (startswith(a, "unixexec:")) {
881 r = parse_exec_address(b, &a, &guid);
887 } else if (startswith(a, "kernel:")) {
890 r = parse_kernel_address(b, &a, &guid);
895 } else if (startswith(a, "x-container-unix:")) {
898 r = parse_container_unix_address(b, &a, &guid);
903 } else if (startswith(a, "x-container-kernel:")) {
906 r = parse_container_kernel_address(b, &a, &guid);
919 r = sd_id128_from_string(guid, &b->server_id);
924 b->address_index = a - b->address;
928 static int bus_start_address(sd_bus *b) {
934 bool skipped = false;
939 r = bus_socket_exec(b);
940 else if (b->machine && b->kernel)
941 r = bus_container_connect_kernel(b);
942 else if (b->machine && b->sockaddr.sa.sa_family != AF_UNSPEC)
943 r = bus_container_connect_socket(b);
945 r = bus_kernel_connect(b);
946 else if (b->sockaddr.sa.sa_family != AF_UNSPEC)
947 r = bus_socket_connect(b);
953 r = attach_io_events(b);
958 b->last_connect_error = -r;
961 r = bus_parse_next_address(b);
965 return b->last_connect_error ? -b->last_connect_error : -ECONNREFUSED;
969 int bus_next_address(sd_bus *b) {
972 bus_reset_parsed_address(b);
973 return bus_start_address(b);
976 static int bus_start_fd(sd_bus *b) {
981 assert(b->input_fd >= 0);
982 assert(b->output_fd >= 0);
984 r = fd_nonblock(b->input_fd, true);
988 r = fd_cloexec(b->input_fd, true);
992 if (b->input_fd != b->output_fd) {
993 r = fd_nonblock(b->output_fd, true);
997 r = fd_cloexec(b->output_fd, true);
1002 if (fstat(b->input_fd, &st) < 0)
1005 if (S_ISCHR(b->input_fd))
1006 return bus_kernel_take_fd(b);
1008 return bus_socket_take_fd(b);
1011 _public_ int sd_bus_start(sd_bus *bus) {
1014 assert_return(bus, -EINVAL);
1015 assert_return(bus->state == BUS_UNSET, -EPERM);
1016 assert_return(!bus_pid_changed(bus), -ECHILD);
1018 bus->state = BUS_OPENING;
1020 if (bus->is_server && bus->bus_client)
1023 if (bus->input_fd >= 0)
1024 r = bus_start_fd(bus);
1025 else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->kernel || bus->machine)
1026 r = bus_start_address(bus);
1033 return bus_send_hello(bus);
1036 _public_ int sd_bus_open_system(sd_bus **ret) {
1041 assert_return(ret, -EINVAL);
1047 e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1049 r = sd_bus_set_address(b, e);
1051 r = sd_bus_set_address(b, DEFAULT_SYSTEM_BUS_PATH);
1055 b->bus_client = true;
1057 /* Let's do per-method access control on the system bus. We
1058 * need the caller's UID and capability set for that. */
1060 b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1062 r = sd_bus_start(b);
1074 _public_ int sd_bus_open_user(sd_bus **ret) {
1079 assert_return(ret, -EINVAL);
1085 e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
1087 r = sd_bus_set_address(b, e);
1091 e = secure_getenv("XDG_RUNTIME_DIR");
1093 _cleanup_free_ char *ee = NULL;
1095 ee = bus_address_escape(e);
1102 asprintf(&b->address, KERNEL_USER_BUS_FMT ";" UNIX_USER_BUS_FMT, (unsigned long) getuid(), ee);
1104 asprintf(&b->address, UNIX_USER_BUS_FMT, ee);
1108 asprintf(&b->address, KERNEL_USER_BUS_FMT, (unsigned long) getuid());
1110 return -ECONNREFUSED;
1120 b->bus_client = true;
1122 /* We don't do any per-method access control on the user
1126 r = sd_bus_start(b);
1138 _public_ int sd_bus_open_system_remote(const char *host, sd_bus **ret) {
1139 _cleanup_free_ char *e = NULL;
1144 assert_return(host, -EINVAL);
1145 assert_return(ret, -EINVAL);
1147 e = bus_address_escape(host);
1151 p = strjoin("unixexec:path=ssh,argv1=-xT,argv2=", e, ",argv3=systemd-stdio-bridge", NULL);
1155 r = sd_bus_new(&bus);
1162 bus->bus_client = true;
1164 r = sd_bus_start(bus);
1174 _public_ int sd_bus_open_system_container(const char *machine, sd_bus **ret) {
1175 _cleanup_free_ char *e = NULL;
1180 assert_return(machine, -EINVAL);
1181 assert_return(ret, -EINVAL);
1182 assert_return(filename_is_safe(machine), -EINVAL);
1184 e = bus_address_escape(machine);
1189 p = strjoin("x-container-kernel:machine=", e, ";x-container-unix:machine=", e, NULL);
1191 p = strjoin("x-container-unix:machine=", e, NULL);
1196 r = sd_bus_new(&bus);
1203 bus->bus_client = true;
1205 r = sd_bus_start(bus);
1215 _public_ void sd_bus_close(sd_bus *bus) {
1219 if (bus->state == BUS_CLOSED)
1221 if (bus_pid_changed(bus))
1224 bus->state = BUS_CLOSED;
1226 sd_bus_detach_event(bus);
1228 /* Drop all queued messages so that they drop references to
1229 * the bus object and the bus may be freed */
1230 bus_reset_queues(bus);
1232 if (!bus->is_kernel)
1235 /* We'll leave the fd open in case this is a kernel bus, since
1236 * there might still be memblocks around that reference this
1237 * bus, and they might need to invoke the KDBUS_CMD_FREE
1238 * ioctl on the fd when they are freed. */
1241 static void bus_enter_closing(sd_bus *bus) {
1244 if (bus->state != BUS_OPENING &&
1245 bus->state != BUS_AUTHENTICATING &&
1246 bus->state != BUS_HELLO &&
1247 bus->state != BUS_RUNNING)
1250 bus->state = BUS_CLOSING;
1253 _public_ sd_bus *sd_bus_ref(sd_bus *bus) {
1254 assert_return(bus, NULL);
1256 assert_se(REFCNT_INC(bus->n_ref) >= 2);
1261 _public_ sd_bus *sd_bus_unref(sd_bus *bus) {
1267 i = REFCNT_DEC(bus->n_ref);
1268 if (i != bus->rqueue_size + bus->wqueue_size)
1271 for (i = 0; i < bus->rqueue_size; i++)
1272 if (bus->rqueue[i]->n_ref > 1)
1275 for (i = 0; i < bus->wqueue_size; i++)
1276 if (bus->wqueue[i]->n_ref > 1)
1279 /* we are the only holders on the messages */
1285 _public_ int sd_bus_is_open(sd_bus *bus) {
1287 assert_return(bus, -EINVAL);
1288 assert_return(!bus_pid_changed(bus), -ECHILD);
1290 return BUS_IS_OPEN(bus->state);
1293 _public_ int sd_bus_can_send(sd_bus *bus, char type) {
1296 assert_return(bus, -EINVAL);
1297 assert_return(bus->state != BUS_UNSET, -ENOTCONN);
1298 assert_return(!bus_pid_changed(bus), -ECHILD);
1300 if (type == SD_BUS_TYPE_UNIX_FD) {
1301 if (!(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD))
1304 r = bus_ensure_running(bus);
1308 return bus->can_fds;
1311 return bus_type_is_valid(type);
1314 _public_ int sd_bus_get_server_id(sd_bus *bus, sd_id128_t *server_id) {
1317 assert_return(bus, -EINVAL);
1318 assert_return(server_id, -EINVAL);
1319 assert_return(!bus_pid_changed(bus), -ECHILD);
1321 r = bus_ensure_running(bus);
1325 *server_id = bus->server_id;
1329 static int bus_seal_message(sd_bus *b, sd_bus_message *m, usec_t timeout) {
1334 /* If we copy the same message to multiple
1335 * destinations, avoid using the same cookie
1337 b->cookie = MAX(b->cookie, BUS_MESSAGE_COOKIE(m));
1342 timeout = BUS_DEFAULT_TIMEOUT;
1344 return bus_message_seal(m, ++b->cookie, timeout);
1347 static int bus_remarshal_message(sd_bus *b, sd_bus_message **m) {
1350 /* Do packet version and endianess already match? */
1351 if ((b->message_version == 0 || b->message_version == (*m)->header->version) &&
1352 (b->message_endian == 0 || b->message_endian == (*m)->header->endian))
1355 /* No? Then remarshal! */
1356 return bus_message_remarshal(b, m);
1359 int bus_seal_synthetic_message(sd_bus *b, sd_bus_message *m) {
1363 /* The bus specification says the serial number cannot be 0,
1364 * hence let's fill something in for synthetic messages. Since
1365 * synthetic messages might have a fake sender and we don't
1366 * want to interfere with the real sender's serial numbers we
1367 * pick a fixed, artifical one. We use (uint32_t) -1 rather
1368 * than (uint64_t) -1 since dbus1 only had 32bit identifiers,
1369 * even though kdbus can do 64bit. */
1371 return bus_message_seal(m, 0xFFFFFFFFULL, 0);
1374 static int bus_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
1381 r = bus_kernel_write_message(bus, m);
1383 r = bus_socket_write_message(bus, m, idx);
1388 if (bus->is_kernel || *idx >= BUS_MESSAGE_SIZE(m))
1389 log_debug("Sent message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%lu reply_cookie=%lu error=%s",
1390 bus_message_type_to_string(m->header->type),
1391 strna(sd_bus_message_get_sender(m)),
1392 strna(sd_bus_message_get_destination(m)),
1393 strna(sd_bus_message_get_path(m)),
1394 strna(sd_bus_message_get_interface(m)),
1395 strna(sd_bus_message_get_member(m)),
1396 (unsigned long) BUS_MESSAGE_COOKIE(m),
1397 (unsigned long) m->reply_cookie,
1398 strna(m->error.message));
1403 static int dispatch_wqueue(sd_bus *bus) {
1407 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1409 while (bus->wqueue_size > 0) {
1411 r = bus_write_message(bus, bus->wqueue[0], &bus->windex);
1415 /* Didn't do anything this time */
1417 else if (bus->is_kernel || bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
1418 /* Fully written. Let's drop the entry from
1421 * This isn't particularly optimized, but
1422 * well, this is supposed to be our worst-case
1423 * buffer only, and the socket buffer is
1424 * supposed to be our primary buffer, and if
1425 * it got full, then all bets are off
1428 bus->wqueue_size --;
1429 sd_bus_message_unref(bus->wqueue[0]);
1430 memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
1440 static int bus_read_message(sd_bus *bus) {
1444 return bus_kernel_read_message(bus);
1446 return bus_socket_read_message(bus);
1449 int bus_rqueue_make_room(sd_bus *bus) {
1452 if (bus->rqueue_size >= BUS_RQUEUE_MAX)
1455 if (!GREEDY_REALLOC(bus->rqueue, bus->rqueue_allocated, bus->rqueue_size + 1))
1461 static int dispatch_rqueue(sd_bus *bus, sd_bus_message **m) {
1466 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1469 if (bus->rqueue_size > 0) {
1470 /* Dispatch a queued message */
1472 *m = bus->rqueue[0];
1473 bus->rqueue_size --;
1474 memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
1478 /* Try to read a new message */
1479 r = bus_read_message(bus);
1489 _public_ int sd_bus_send(sd_bus *bus, sd_bus_message *_m, uint64_t *cookie) {
1490 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1493 assert_return(bus, -EINVAL);
1494 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1495 assert_return(m, -EINVAL);
1496 assert_return(!bus_pid_changed(bus), -ECHILD);
1499 r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
1506 /* If the cookie number isn't kept, then we know that no reply
1508 if (!cookie && !m->sealed)
1509 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1511 r = bus_seal_message(bus, m, 0);
1515 /* Remarshall if we have to. This will possibly unref the
1516 * message and place a replacement in m */
1517 r = bus_remarshal_message(bus, &m);
1521 /* If this is a reply and no reply was requested, then let's
1522 * suppress this, if we can */
1523 if (m->dont_send && !cookie)
1526 if ((bus->state == BUS_RUNNING || bus->state == BUS_HELLO) && bus->wqueue_size <= 0) {
1529 r = bus_write_message(bus, m, &idx);
1531 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
1532 bus_enter_closing(bus);
1537 } else if (!bus->is_kernel && idx < BUS_MESSAGE_SIZE(m)) {
1538 /* Wasn't fully written. So let's remember how
1539 * much was written. Note that the first entry
1540 * of the wqueue array is always allocated so
1541 * that we always can remember how much was
1543 bus->wqueue[0] = sd_bus_message_ref(m);
1544 bus->wqueue_size = 1;
1548 /* Just append it to the queue. */
1550 if (bus->wqueue_size >= BUS_WQUEUE_MAX)
1553 if (!GREEDY_REALLOC(bus->wqueue, bus->wqueue_allocated, bus->wqueue_size + 1))
1556 bus->wqueue[bus->wqueue_size ++] = sd_bus_message_ref(m);
1560 *cookie = BUS_MESSAGE_COOKIE(m);
1565 _public_ int sd_bus_send_to(sd_bus *bus, sd_bus_message *m, const char *destination, uint64_t *cookie) {
1568 assert_return(bus, -EINVAL);
1569 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1570 assert_return(m, -EINVAL);
1571 assert_return(!bus_pid_changed(bus), -ECHILD);
1573 if (!streq_ptr(m->destination, destination)) {
1578 r = sd_bus_message_set_destination(m, destination);
1583 return sd_bus_send(bus, m, cookie);
1586 static usec_t calc_elapse(uint64_t usec) {
1587 if (usec == (uint64_t) -1)
1590 return now(CLOCK_MONOTONIC) + usec;
1593 static int timeout_compare(const void *a, const void *b) {
1594 const struct reply_callback *x = a, *y = b;
1596 if (x->timeout != 0 && y->timeout == 0)
1599 if (x->timeout == 0 && y->timeout != 0)
1602 if (x->timeout < y->timeout)
1605 if (x->timeout > y->timeout)
1611 _public_ int sd_bus_call_async(
1614 sd_bus_message_handler_t callback,
1619 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1620 struct reply_callback *c;
1623 assert_return(bus, -EINVAL);
1624 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1625 assert_return(m, -EINVAL);
1626 assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1627 assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1628 assert_return(callback, -EINVAL);
1629 assert_return(!bus_pid_changed(bus), -ECHILD);
1631 r = hashmap_ensure_allocated(&bus->reply_callbacks, uint64_hash_func, uint64_compare_func);
1635 r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
1639 r = bus_seal_message(bus, m, usec);
1643 r = bus_remarshal_message(bus, &m);
1647 c = new0(struct reply_callback, 1);
1651 c->callback = callback;
1652 c->userdata = userdata;
1653 c->cookie = BUS_MESSAGE_COOKIE(m);
1654 c->timeout = calc_elapse(m->timeout);
1656 r = hashmap_put(bus->reply_callbacks, &c->cookie, c);
1662 if (c->timeout != 0) {
1663 r = prioq_put(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1666 sd_bus_call_async_cancel(bus, c->cookie);
1671 r = sd_bus_send(bus, m, cookie);
1673 sd_bus_call_async_cancel(bus, c->cookie);
1680 _public_ int sd_bus_call_async_cancel(sd_bus *bus, uint64_t cookie) {
1681 struct reply_callback *c;
1683 assert_return(bus, -EINVAL);
1684 assert_return(cookie != 0, -EINVAL);
1685 assert_return(!bus_pid_changed(bus), -ECHILD);
1687 c = hashmap_remove(bus->reply_callbacks, &cookie);
1691 if (c->timeout != 0)
1692 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1698 int bus_ensure_running(sd_bus *bus) {
1703 if (bus->state == BUS_UNSET || bus->state == BUS_CLOSED || bus->state == BUS_CLOSING)
1705 if (bus->state == BUS_RUNNING)
1709 r = sd_bus_process(bus, NULL);
1712 if (bus->state == BUS_RUNNING)
1717 r = sd_bus_wait(bus, (uint64_t) -1);
1723 static int bus_call_dbus1(
1727 sd_bus_error *error,
1728 sd_bus_message **reply) {
1735 i = bus->rqueue_size;
1736 r = sd_bus_send(bus, m, &cookie);
1740 timeout = calc_elapse(m->timeout);
1745 while (i < bus->rqueue_size) {
1746 sd_bus_message *incoming = NULL;
1748 incoming = bus->rqueue[i];
1750 if (incoming->reply_cookie == cookie) {
1751 /* Found a match! */
1753 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1756 if (incoming->header->type == SD_BUS_MESSAGE_METHOD_RETURN) {
1761 sd_bus_message_unref(incoming);
1764 } else if (incoming->header->type == SD_BUS_MESSAGE_METHOD_ERROR)
1765 r = sd_bus_error_copy(error, &incoming->error);
1769 sd_bus_message_unref(incoming);
1772 } else if (BUS_MESSAGE_COOKIE(incoming) == cookie &&
1775 streq(bus->unique_name, incoming->sender)) {
1777 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1780 /* Our own message? Somebody is trying
1781 * to send its own client a message,
1782 * let's not dead-lock, let's fail
1785 sd_bus_message_unref(incoming);
1789 /* Try to read more, right-away */
1793 r = bus_read_message(bus);
1795 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
1796 bus_enter_closing(bus);
1808 n = now(CLOCK_MONOTONIC);
1814 left = (uint64_t) -1;
1816 r = bus_poll(bus, true, left);
1822 r = dispatch_wqueue(bus);
1824 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
1825 bus_enter_closing(bus);
1834 _public_ int sd_bus_call(
1838 sd_bus_error *error,
1839 sd_bus_message **reply) {
1841 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1844 assert_return(bus, -EINVAL);
1845 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1846 assert_return(m, -EINVAL);
1847 assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1848 assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1849 assert_return(!bus_error_is_dirty(error), -EINVAL);
1850 assert_return(!bus_pid_changed(bus), -ECHILD);
1852 r = bus_ensure_running(bus);
1856 r = bus_seal_message(bus, m, usec);
1860 r = bus_remarshal_message(bus, &m);
1865 return bus_call_kernel(bus, m, usec, error, reply);
1867 return bus_call_dbus1(bus, m, usec, error, reply);
1870 _public_ int sd_bus_get_fd(sd_bus *bus) {
1872 assert_return(bus, -EINVAL);
1873 assert_return(bus->input_fd == bus->output_fd, -EPERM);
1874 assert_return(!bus_pid_changed(bus), -ECHILD);
1876 return bus->input_fd;
1879 _public_ int sd_bus_get_events(sd_bus *bus) {
1882 assert_return(bus, -EINVAL);
1883 assert_return(BUS_IS_OPEN(bus->state) || bus->state == BUS_CLOSING, -ENOTCONN);
1884 assert_return(!bus_pid_changed(bus), -ECHILD);
1886 if (bus->state == BUS_OPENING)
1888 else if (bus->state == BUS_AUTHENTICATING) {
1890 if (bus_socket_auth_needs_write(bus))
1895 } else if (bus->state == BUS_RUNNING || bus->state == BUS_HELLO) {
1896 if (bus->rqueue_size <= 0)
1898 if (bus->wqueue_size > 0)
1905 _public_ int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
1906 struct reply_callback *c;
1908 assert_return(bus, -EINVAL);
1909 assert_return(timeout_usec, -EINVAL);
1910 assert_return(BUS_IS_OPEN(bus->state) || bus->state == BUS_CLOSING, -ENOTCONN);
1911 assert_return(!bus_pid_changed(bus), -ECHILD);
1913 if (bus->state == BUS_CLOSING) {
1918 if (bus->state == BUS_AUTHENTICATING) {
1919 *timeout_usec = bus->auth_timeout;
1923 if (bus->state != BUS_RUNNING && bus->state != BUS_HELLO) {
1924 *timeout_usec = (uint64_t) -1;
1928 if (bus->rqueue_size > 0) {
1933 c = prioq_peek(bus->reply_callbacks_prioq);
1935 *timeout_usec = (uint64_t) -1;
1939 *timeout_usec = c->timeout;
1943 static int process_timeout(sd_bus *bus) {
1944 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
1945 _cleanup_bus_message_unref_ sd_bus_message* m = NULL;
1946 struct reply_callback *c;
1952 c = prioq_peek(bus->reply_callbacks_prioq);
1956 n = now(CLOCK_MONOTONIC);
1960 r = bus_message_new_synthetic_error(
1963 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
1968 m->sender = "org.freedesktop.DBus";
1970 r = bus_seal_synthetic_message(bus, m);
1974 assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
1975 hashmap_remove(bus->reply_callbacks, &c->cookie);
1978 bus->iteration_counter ++;
1980 r = c->callback(bus, m, c->userdata, &error_buffer);
1981 r = bus_maybe_reply_error(m, r, &error_buffer);
1984 bus->current = NULL;
1989 static int process_hello(sd_bus *bus, sd_bus_message *m) {
1993 if (bus->state != BUS_HELLO)
1996 /* Let's make sure the first message on the bus is the HELLO
1997 * reply. But note that we don't actually parse the message
1998 * here (we leave that to the usual handling), we just verify
1999 * we don't let any earlier msg through. */
2001 if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2002 m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2005 if (m->reply_cookie != bus->hello_cookie)
2011 static int process_reply(sd_bus *bus, sd_bus_message *m) {
2012 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2013 struct reply_callback *c;
2019 if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2020 m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2023 c = hashmap_remove(bus->reply_callbacks, &m->reply_cookie);
2027 if (c->timeout != 0)
2028 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2030 r = sd_bus_message_rewind(m, true);
2034 r = c->callback(bus, m, c->userdata, &error_buffer);
2035 r = bus_maybe_reply_error(m, r, &error_buffer);
2041 static int process_filter(sd_bus *bus, sd_bus_message *m) {
2042 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2043 struct filter_callback *l;
2050 bus->filter_callbacks_modified = false;
2052 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
2054 if (bus->filter_callbacks_modified)
2057 /* Don't run this more than once per iteration */
2058 if (l->last_iteration == bus->iteration_counter)
2061 l->last_iteration = bus->iteration_counter;
2063 r = sd_bus_message_rewind(m, true);
2067 r = l->callback(bus, m, l->userdata, &error_buffer);
2068 r = bus_maybe_reply_error(m, r, &error_buffer);
2074 } while (bus->filter_callbacks_modified);
2079 static int process_match(sd_bus *bus, sd_bus_message *m) {
2086 bus->match_callbacks_modified = false;
2088 r = bus_match_run(bus, &bus->match_callbacks, m);
2092 } while (bus->match_callbacks_modified);
2097 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
2098 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2104 if (bus->manual_peer_interface)
2107 if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2110 if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2113 if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2116 if (streq_ptr(m->member, "Ping"))
2117 r = sd_bus_message_new_method_return(m, &reply);
2118 else if (streq_ptr(m->member, "GetMachineId")) {
2122 r = sd_id128_get_machine(&id);
2126 r = sd_bus_message_new_method_return(m, &reply);
2130 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2132 r = sd_bus_message_new_method_errorf(
2134 SD_BUS_ERROR_UNKNOWN_METHOD,
2135 "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2141 r = sd_bus_send(bus, reply, NULL);
2148 static int process_message(sd_bus *bus, sd_bus_message *m) {
2155 bus->iteration_counter++;
2157 log_debug("Got message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%lu reply_cookie=%lu error=%s",
2158 bus_message_type_to_string(m->header->type),
2159 strna(sd_bus_message_get_sender(m)),
2160 strna(sd_bus_message_get_destination(m)),
2161 strna(sd_bus_message_get_path(m)),
2162 strna(sd_bus_message_get_interface(m)),
2163 strna(sd_bus_message_get_member(m)),
2164 (unsigned long) BUS_MESSAGE_COOKIE(m),
2165 (unsigned long) m->reply_cookie,
2166 strna(m->error.message));
2168 r = process_hello(bus, m);
2172 r = process_reply(bus, m);
2176 r = process_filter(bus, m);
2180 r = process_match(bus, m);
2184 r = process_builtin(bus, m);
2188 r = bus_process_object(bus, m);
2191 bus->current = NULL;
2195 static int process_running(sd_bus *bus, sd_bus_message **ret) {
2196 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2200 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
2202 r = process_timeout(bus);
2206 r = dispatch_wqueue(bus);
2210 r = dispatch_rqueue(bus, &m);
2216 r = process_message(bus, m);
2221 r = sd_bus_message_rewind(m, true);
2230 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2232 log_debug("Unprocessed message call sender=%s object=%s interface=%s member=%s",
2233 strna(sd_bus_message_get_sender(m)),
2234 strna(sd_bus_message_get_path(m)),
2235 strna(sd_bus_message_get_interface(m)),
2236 strna(sd_bus_message_get_member(m)));
2238 r = sd_bus_reply_method_errorf(
2240 SD_BUS_ERROR_UNKNOWN_OBJECT,
2241 "Unknown object '%s'.", m->path);
2255 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2256 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2257 struct reply_callback *c;
2261 assert(bus->state == BUS_CLOSING);
2263 c = hashmap_first(bus->reply_callbacks);
2265 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2267 /* First, fail all outstanding method calls */
2268 r = bus_message_new_synthetic_error(
2271 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2276 r = bus_seal_synthetic_message(bus, m);
2280 if (c->timeout != 0)
2281 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2283 hashmap_remove(bus->reply_callbacks, &c->cookie);
2286 bus->iteration_counter++;
2288 r = c->callback(bus, m, c->userdata, &error_buffer);
2289 r = bus_maybe_reply_error(m, r, &error_buffer);
2295 /* Then, synthesize a Disconnected message */
2296 r = sd_bus_message_new_signal(
2298 "/org/freedesktop/DBus/Local",
2299 "org.freedesktop.DBus.Local",
2305 m->sender = "org.freedesktop.DBus.Local";
2307 r = bus_seal_synthetic_message(bus, m);
2314 bus->iteration_counter++;
2316 r = process_filter(bus, m);
2320 r = process_match(bus, m);
2332 bus->current = NULL;
2336 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2337 BUS_DONT_DESTROY(bus);
2340 /* Returns 0 when we didn't do anything. This should cause the
2341 * caller to invoke sd_bus_wait() before returning the next
2342 * time. Returns > 0 when we did something, which possibly
2343 * means *ret is filled in with an unprocessed message. */
2345 assert_return(bus, -EINVAL);
2346 assert_return(!bus_pid_changed(bus), -ECHILD);
2348 /* We don't allow recursively invoking sd_bus_process(). */
2349 assert_return(!bus->current, -EBUSY);
2351 switch (bus->state) {
2360 r = bus_socket_process_opening(bus);
2361 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2362 bus_enter_closing(bus);
2370 case BUS_AUTHENTICATING:
2371 r = bus_socket_process_authenticating(bus);
2372 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2373 bus_enter_closing(bus);
2385 r = process_running(bus, ret);
2386 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2387 bus_enter_closing(bus);
2397 return process_closing(bus, ret);
2400 assert_not_reached("Unknown state");
2403 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2404 struct pollfd p[2] = {};
2407 usec_t m = (usec_t) -1;
2411 if (bus->state == BUS_CLOSING)
2414 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2416 e = sd_bus_get_events(bus);
2421 /* The caller really needs some more data, he doesn't
2422 * care about what's already read, or any timeouts
2427 /* The caller wants to process if there's something to
2428 * process, but doesn't care otherwise */
2430 r = sd_bus_get_timeout(bus, &until);
2435 nw = now(CLOCK_MONOTONIC);
2436 m = until > nw ? until - nw : 0;
2440 if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
2443 p[0].fd = bus->input_fd;
2444 if (bus->output_fd == bus->input_fd) {
2448 p[0].events = e & POLLIN;
2449 p[1].fd = bus->output_fd;
2450 p[1].events = e & POLLOUT;
2454 r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
2458 return r > 0 ? 1 : 0;
2461 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
2463 assert_return(bus, -EINVAL);
2464 assert_return(!bus_pid_changed(bus), -ECHILD);
2466 if (bus->state == BUS_CLOSING)
2469 assert_return(BUS_IS_OPEN(bus->state) , -ENOTCONN);
2471 if (bus->rqueue_size > 0)
2474 return bus_poll(bus, false, timeout_usec);
2477 _public_ int sd_bus_flush(sd_bus *bus) {
2480 assert_return(bus, -EINVAL);
2481 assert_return(!bus_pid_changed(bus), -ECHILD);
2483 if (bus->state == BUS_CLOSING)
2486 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2488 r = bus_ensure_running(bus);
2492 if (bus->wqueue_size <= 0)
2496 r = dispatch_wqueue(bus);
2498 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2499 bus_enter_closing(bus);
2506 if (bus->wqueue_size <= 0)
2509 r = bus_poll(bus, false, (uint64_t) -1);
2515 _public_ int sd_bus_add_filter(sd_bus *bus,
2516 sd_bus_message_handler_t callback,
2519 struct filter_callback *f;
2521 assert_return(bus, -EINVAL);
2522 assert_return(callback, -EINVAL);
2523 assert_return(!bus_pid_changed(bus), -ECHILD);
2525 f = new0(struct filter_callback, 1);
2528 f->callback = callback;
2529 f->userdata = userdata;
2531 bus->filter_callbacks_modified = true;
2532 LIST_PREPEND(callbacks, bus->filter_callbacks, f);
2536 _public_ int sd_bus_remove_filter(sd_bus *bus,
2537 sd_bus_message_handler_t callback,
2540 struct filter_callback *f;
2542 assert_return(bus, -EINVAL);
2543 assert_return(callback, -EINVAL);
2544 assert_return(!bus_pid_changed(bus), -ECHILD);
2546 LIST_FOREACH(callbacks, f, bus->filter_callbacks) {
2547 if (f->callback == callback && f->userdata == userdata) {
2548 bus->filter_callbacks_modified = true;
2549 LIST_REMOVE(callbacks, bus->filter_callbacks, f);
2558 _public_ int sd_bus_add_match(sd_bus *bus,
2560 sd_bus_message_handler_t callback,
2563 struct bus_match_component *components = NULL;
2564 unsigned n_components = 0;
2565 uint64_t cookie = 0;
2568 assert_return(bus, -EINVAL);
2569 assert_return(match, -EINVAL);
2570 assert_return(!bus_pid_changed(bus), -ECHILD);
2572 r = bus_match_parse(match, &components, &n_components);
2576 if (bus->bus_client) {
2577 cookie = ++bus->match_cookie;
2579 r = bus_add_match_internal(bus, match, components, n_components, cookie);
2584 bus->match_callbacks_modified = true;
2585 r = bus_match_add(&bus->match_callbacks, components, n_components, callback, userdata, cookie, NULL);
2587 if (bus->bus_client)
2588 bus_remove_match_internal(bus, match, cookie);
2592 bus_match_parse_free(components, n_components);
2596 _public_ int sd_bus_remove_match(sd_bus *bus,
2598 sd_bus_message_handler_t callback,
2601 struct bus_match_component *components = NULL;
2602 unsigned n_components = 0;
2604 uint64_t cookie = 0;
2606 assert_return(bus, -EINVAL);
2607 assert_return(match, -EINVAL);
2608 assert_return(!bus_pid_changed(bus), -ECHILD);
2610 r = bus_match_parse(match, &components, &n_components);
2614 bus->match_callbacks_modified = true;
2615 r = bus_match_remove(&bus->match_callbacks, components, n_components, callback, userdata, &cookie);
2617 if (bus->bus_client)
2618 q = bus_remove_match_internal(bus, match, cookie);
2620 bus_match_parse_free(components, n_components);
2622 return r < 0 ? r : q;
2625 bool bus_pid_changed(sd_bus *bus) {
2628 /* We don't support people creating a bus connection and
2629 * keeping it around over a fork(). Let's complain. */
2631 return bus->original_pid != getpid();
2634 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2635 sd_bus *bus = userdata;
2640 r = sd_bus_process(bus, NULL);
2647 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
2648 sd_bus *bus = userdata;
2653 r = sd_bus_process(bus, NULL);
2660 static int prepare_callback(sd_event_source *s, void *userdata) {
2661 sd_bus *bus = userdata;
2668 e = sd_bus_get_events(bus);
2672 if (bus->output_fd != bus->input_fd) {
2674 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
2678 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
2682 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
2687 r = sd_bus_get_timeout(bus, &until);
2693 j = sd_event_source_set_time(bus->time_event_source, until);
2698 r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
2705 static int quit_callback(sd_event_source *event, void *userdata) {
2706 sd_bus *bus = userdata;
2715 static int attach_io_events(sd_bus *bus) {
2720 if (bus->input_fd < 0)
2726 if (!bus->input_io_event_source) {
2727 r = sd_event_add_io(bus->event, bus->input_fd, 0, io_callback, bus, &bus->input_io_event_source);
2731 r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
2735 r = sd_event_source_set_priority(bus->input_io_event_source, bus->event_priority);
2737 r = sd_event_source_set_io_fd(bus->input_io_event_source, bus->input_fd);
2742 if (bus->output_fd != bus->input_fd) {
2743 assert(bus->output_fd >= 0);
2745 if (!bus->output_io_event_source) {
2746 r = sd_event_add_io(bus->event, bus->output_fd, 0, io_callback, bus, &bus->output_io_event_source);
2750 r = sd_event_source_set_priority(bus->output_io_event_source, bus->event_priority);
2752 r = sd_event_source_set_io_fd(bus->output_io_event_source, bus->output_fd);
2761 static void detach_io_events(sd_bus *bus) {
2764 if (bus->input_io_event_source) {
2765 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
2766 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
2769 if (bus->output_io_event_source) {
2770 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
2771 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
2775 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
2778 assert_return(bus, -EINVAL);
2779 assert_return(!bus->event, -EBUSY);
2781 assert(!bus->input_io_event_source);
2782 assert(!bus->output_io_event_source);
2783 assert(!bus->time_event_source);
2786 bus->event = sd_event_ref(event);
2788 r = sd_event_default(&bus->event);
2793 bus->event_priority = priority;
2795 r = sd_event_add_monotonic(bus->event, 0, 0, time_callback, bus, &bus->time_event_source);
2799 r = sd_event_source_set_priority(bus->time_event_source, priority);
2803 r = sd_event_add_exit(bus->event, quit_callback, bus, &bus->quit_event_source);
2807 r = attach_io_events(bus);
2814 sd_bus_detach_event(bus);
2818 _public_ int sd_bus_detach_event(sd_bus *bus) {
2819 assert_return(bus, -EINVAL);
2824 detach_io_events(bus);
2826 if (bus->time_event_source) {
2827 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
2828 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
2831 if (bus->quit_event_source) {
2832 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
2833 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
2837 bus->event = sd_event_unref(bus->event);
2842 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
2843 assert_return(bus, NULL);
2848 _public_ sd_bus_message* sd_bus_get_current(sd_bus *bus) {
2849 assert_return(bus, NULL);
2851 return bus->current;
2854 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
2859 assert(default_bus);
2862 return !!*default_bus;
2865 *ret = sd_bus_ref(*default_bus);
2873 b->default_bus_ptr = default_bus;
2881 _public_ int sd_bus_default_system(sd_bus **ret) {
2882 static thread_local sd_bus *default_system_bus = NULL;
2884 return bus_default(sd_bus_open_system, &default_system_bus, ret);
2887 _public_ int sd_bus_default_user(sd_bus **ret) {
2888 static thread_local sd_bus *default_user_bus = NULL;
2890 return bus_default(sd_bus_open_user, &default_user_bus, ret);
2893 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
2894 assert_return(b, -EINVAL);
2895 assert_return(tid, -EINVAL);
2896 assert_return(!bus_pid_changed(b), -ECHILD);
2904 return sd_event_get_tid(b->event, tid);
2909 _public_ char *sd_bus_label_escape(const char *s) {
2913 assert_return(s, NULL);
2915 /* Escapes all chars that D-Bus' object path cannot deal
2916 * with. Can be reversed with bus_path_unescape(). We special
2917 * case the empty string. */
2922 r = new(char, strlen(s)*3 + 1);
2926 for (f = s, t = r; *f; f++) {
2928 /* Escape everything that is not a-zA-Z0-9. We also
2929 * escape 0-9 if it's the first character */
2931 if (!(*f >= 'A' && *f <= 'Z') &&
2932 !(*f >= 'a' && *f <= 'z') &&
2933 !(f > s && *f >= '0' && *f <= '9')) {
2935 *(t++) = hexchar(*f >> 4);
2936 *(t++) = hexchar(*f);
2946 _public_ char *sd_bus_label_unescape(const char *f) {
2949 assert_return(f, NULL);
2951 /* Special case for the empty string */
2955 r = new(char, strlen(f) + 1);
2959 for (t = r; *f; f++) {
2964 if ((a = unhexchar(f[1])) < 0 ||
2965 (b = unhexchar(f[2])) < 0) {
2966 /* Invalid escape code, let's take it literal then */
2969 *(t++) = (char) ((a << 4) | b);
2981 _public_ int sd_bus_get_peer_creds(sd_bus *bus, uint64_t mask, sd_bus_creds **ret) {
2986 assert_return(bus, -EINVAL);
2987 assert_return(mask <= _SD_BUS_CREDS_ALL, -ENOTSUP);
2988 assert_return(ret, -EINVAL);
2989 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2990 assert_return(!bus_pid_changed(bus), -ECHILD);
2991 assert_return(!bus->is_kernel, -ENOTSUP);
2993 if (!bus->ucred_valid && !isempty(bus->label))
2996 c = bus_creds_new();
3000 if (bus->ucred_valid) {
3001 pid = c->pid = bus->ucred.pid;
3002 c->uid = bus->ucred.uid;
3003 c->gid = bus->ucred.gid;
3005 c->mask |= (SD_BUS_CREDS_UID | SD_BUS_CREDS_PID | SD_BUS_CREDS_GID) & mask;
3008 if (!isempty(bus->label) && (mask & SD_BUS_CREDS_SELINUX_CONTEXT)) {
3009 c->label = strdup(bus->label);
3011 sd_bus_creds_unref(c);
3015 c->mask |= SD_BUS_CREDS_SELINUX_CONTEXT;
3018 r = bus_creds_add_more(c, mask, pid, 0);
3026 _public_ int sd_bus_try_close(sd_bus *bus) {
3029 assert_return(bus, -EINVAL);
3030 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
3031 assert_return(!bus_pid_changed(bus), -ECHILD);
3032 assert_return(bus->is_kernel, -ENOTSUP);
3034 if (bus->rqueue_size > 0)
3037 if (bus->wqueue_size > 0)
3040 r = bus_kernel_try_close(bus);