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/>.
39 #include "bus-internal.h"
40 #include "bus-message.h"
42 #include "bus-socket.h"
43 #include "bus-kernel.h"
44 #include "bus-control.h"
45 #include "bus-introspect.h"
46 #include "bus-signature.h"
47 #include "bus-objects.h"
49 #include "bus-container.h"
50 #include "bus-protocol.h"
52 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec);
53 static int attach_io_events(sd_bus *b);
54 static void detach_io_events(sd_bus *b);
56 static void bus_close_fds(sd_bus *b) {
62 close_nointr_nofail(b->input_fd);
64 if (b->output_fd >= 0 && b->output_fd != b->input_fd)
65 close_nointr_nofail(b->output_fd);
67 b->input_fd = b->output_fd = -1;
70 static void bus_node_destroy(sd_bus *b, struct node *n) {
71 struct node_callback *c;
72 struct node_vtable *v;
73 struct node_enumerator *e;
81 bus_node_destroy(b, n->child);
83 while ((c = n->callbacks)) {
84 LIST_REMOVE(callbacks, n->callbacks, c);
88 while ((v = n->vtables)) {
89 LIST_REMOVE(vtables, n->vtables, v);
94 while ((e = n->enumerators)) {
95 LIST_REMOVE(enumerators, n->enumerators, e);
100 LIST_REMOVE(siblings, n->parent->child, n);
102 assert_se(hashmap_remove(b->nodes, n->path) == n);
107 static void bus_reset_queues(sd_bus *b) {
112 for (i = 0; i < b->rqueue_size; i++)
113 sd_bus_message_unref(b->rqueue[i]);
116 for (i = 0; i < b->wqueue_size; i++)
117 sd_bus_message_unref(b->wqueue[i]);
120 b->rqueue = b->wqueue = NULL;
121 b->rqueue_allocated = b->wqueue_allocated = 0;
122 b->rqueue_size = b->wqueue_size = 0;
125 static void bus_free(sd_bus *b) {
126 struct filter_callback *f;
131 sd_bus_detach_event(b);
136 munmap(b->kdbus_buffer, KDBUS_POOL_SIZE);
139 free(b->unique_name);
140 free(b->auth_buffer);
147 strv_free(b->exec_argv);
149 close_many(b->fds, b->n_fds);
154 hashmap_free_free(b->reply_callbacks);
155 prioq_free(b->reply_callbacks_prioq);
157 while ((f = b->filter_callbacks)) {
158 LIST_REMOVE(callbacks, b->filter_callbacks, f);
162 bus_match_free(&b->match_callbacks);
164 hashmap_free_free(b->vtable_methods);
165 hashmap_free_free(b->vtable_properties);
167 while ((n = hashmap_first(b->nodes)))
168 bus_node_destroy(b, n);
170 hashmap_free(b->nodes);
172 bus_kernel_flush_memfd(b);
174 assert_se(pthread_mutex_destroy(&b->memfd_cache_mutex) == 0);
179 _public_ int sd_bus_new(sd_bus **ret) {
182 assert_return(ret, -EINVAL);
188 r->n_ref = REFCNT_INIT;
189 r->input_fd = r->output_fd = -1;
190 r->message_version = 1;
191 r->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
192 r->hello_flags |= KDBUS_HELLO_ACCEPT_FD;
193 r->attach_flags |= KDBUS_ATTACH_NAMES;
194 r->original_pid = getpid();
196 assert_se(pthread_mutex_init(&r->memfd_cache_mutex, NULL) == 0);
198 /* We guarantee that wqueue always has space for at least one
200 if (!GREEDY_REALLOC(r->wqueue, r->wqueue_allocated, 1)) {
209 _public_ int sd_bus_set_address(sd_bus *bus, const char *address) {
212 assert_return(bus, -EINVAL);
213 assert_return(bus->state == BUS_UNSET, -EPERM);
214 assert_return(address, -EINVAL);
215 assert_return(!bus_pid_changed(bus), -ECHILD);
227 _public_ int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd) {
228 assert_return(bus, -EINVAL);
229 assert_return(bus->state == BUS_UNSET, -EPERM);
230 assert_return(input_fd >= 0, -EINVAL);
231 assert_return(output_fd >= 0, -EINVAL);
232 assert_return(!bus_pid_changed(bus), -ECHILD);
234 bus->input_fd = input_fd;
235 bus->output_fd = output_fd;
239 _public_ int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]) {
242 assert_return(bus, -EINVAL);
243 assert_return(bus->state == BUS_UNSET, -EPERM);
244 assert_return(path, -EINVAL);
245 assert_return(!strv_isempty(argv), -EINVAL);
246 assert_return(!bus_pid_changed(bus), -ECHILD);
258 free(bus->exec_path);
259 strv_free(bus->exec_argv);
267 _public_ int sd_bus_set_bus_client(sd_bus *bus, int b) {
268 assert_return(bus, -EINVAL);
269 assert_return(bus->state == BUS_UNSET, -EPERM);
270 assert_return(!bus_pid_changed(bus), -ECHILD);
272 bus->bus_client = !!b;
276 _public_ int sd_bus_negotiate_fds(sd_bus *bus, int b) {
277 assert_return(bus, -EINVAL);
278 assert_return(bus->state == BUS_UNSET, -EPERM);
279 assert_return(!bus_pid_changed(bus), -ECHILD);
281 SET_FLAG(bus->hello_flags, KDBUS_HELLO_ACCEPT_FD, b);
285 _public_ int sd_bus_negotiate_attach_timestamp(sd_bus *bus, int b) {
286 assert_return(bus, -EINVAL);
287 assert_return(bus->state == BUS_UNSET, -EPERM);
288 assert_return(!bus_pid_changed(bus), -ECHILD);
290 SET_FLAG(bus->attach_flags, KDBUS_ATTACH_TIMESTAMP, b);
294 _public_ int sd_bus_negotiate_attach_creds(sd_bus *bus, uint64_t mask) {
295 assert_return(bus, -EINVAL);
296 assert_return(mask <= _SD_BUS_CREDS_ALL, -EINVAL);
297 assert_return(bus->state == BUS_UNSET, -EPERM);
298 assert_return(!bus_pid_changed(bus), -ECHILD);
300 /* The well knowns we need unconditionally, so that matches can work */
301 bus->creds_mask = mask | SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
303 return kdbus_translate_attach_flags(bus->creds_mask, &bus->creds_mask);
306 _public_ int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id) {
307 assert_return(bus, -EINVAL);
308 assert_return(b || sd_id128_equal(server_id, SD_ID128_NULL), -EINVAL);
309 assert_return(bus->state == BUS_UNSET, -EPERM);
310 assert_return(!bus_pid_changed(bus), -ECHILD);
312 bus->is_server = !!b;
313 bus->server_id = server_id;
317 _public_ int sd_bus_set_anonymous(sd_bus *bus, int b) {
318 assert_return(bus, -EINVAL);
319 assert_return(bus->state == BUS_UNSET, -EPERM);
320 assert_return(!bus_pid_changed(bus), -ECHILD);
322 bus->anonymous_auth = !!b;
326 _public_ int sd_bus_set_trusted(sd_bus *bus, int b) {
327 assert_return(bus, -EINVAL);
328 assert_return(bus->state == BUS_UNSET, -EPERM);
329 assert_return(!bus_pid_changed(bus), -ECHILD);
335 static int hello_callback(sd_bus *bus, sd_bus_message *reply, void *userdata, sd_bus_error *error) {
340 assert(bus->state == BUS_HELLO || bus->state == BUS_CLOSING);
343 r = sd_bus_message_get_errno(reply);
349 r = sd_bus_message_read(reply, "s", &s);
353 if (!service_name_is_valid(s) || s[0] != ':')
356 bus->unique_name = strdup(s);
357 if (!bus->unique_name)
360 if (bus->state == BUS_HELLO)
361 bus->state = BUS_RUNNING;
366 static int bus_send_hello(sd_bus *bus) {
367 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
372 if (!bus->bus_client || bus->is_kernel)
375 r = sd_bus_message_new_method_call(
377 "org.freedesktop.DBus",
378 "/org/freedesktop/DBus",
379 "org.freedesktop.DBus",
385 return sd_bus_call_async(bus, m, hello_callback, NULL, 0, &bus->hello_serial);
388 int bus_start_running(sd_bus *bus) {
391 if (bus->bus_client && !bus->is_kernel) {
392 bus->state = BUS_HELLO;
396 bus->state = BUS_RUNNING;
400 static int parse_address_key(const char **p, const char *key, char **value) {
401 size_t l, n = 0, allocated = 0;
411 if (strncmp(*p, key, l) != 0)
424 while (*a != ';' && *a != ',' && *a != 0) {
442 c = (char) ((x << 4) | y);
449 if (!GREEDY_REALLOC(r, allocated, n + 2))
473 static void skip_address_key(const char **p) {
477 *p += strcspn(*p, ",");
483 static int parse_unix_address(sd_bus *b, const char **p, char **guid) {
484 _cleanup_free_ char *path = NULL, *abstract = NULL;
493 while (**p != 0 && **p != ';') {
494 r = parse_address_key(p, "guid", guid);
500 r = parse_address_key(p, "path", &path);
506 r = parse_address_key(p, "abstract", &abstract);
515 if (!path && !abstract)
518 if (path && abstract)
523 if (l > sizeof(b->sockaddr.un.sun_path))
526 b->sockaddr.un.sun_family = AF_UNIX;
527 strncpy(b->sockaddr.un.sun_path, path, sizeof(b->sockaddr.un.sun_path));
528 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l;
529 } else if (abstract) {
530 l = strlen(abstract);
531 if (l > sizeof(b->sockaddr.un.sun_path) - 1)
534 b->sockaddr.un.sun_family = AF_UNIX;
535 b->sockaddr.un.sun_path[0] = 0;
536 strncpy(b->sockaddr.un.sun_path+1, abstract, sizeof(b->sockaddr.un.sun_path)-1);
537 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
543 static int parse_tcp_address(sd_bus *b, const char **p, char **guid) {
544 _cleanup_free_ char *host = NULL, *port = NULL, *family = NULL;
546 struct addrinfo *result, hints = {
547 .ai_socktype = SOCK_STREAM,
548 .ai_flags = AI_ADDRCONFIG,
556 while (**p != 0 && **p != ';') {
557 r = parse_address_key(p, "guid", guid);
563 r = parse_address_key(p, "host", &host);
569 r = parse_address_key(p, "port", &port);
575 r = parse_address_key(p, "family", &family);
588 if (streq(family, "ipv4"))
589 hints.ai_family = AF_INET;
590 else if (streq(family, "ipv6"))
591 hints.ai_family = AF_INET6;
596 r = getaddrinfo(host, port, &hints, &result);
600 return -EADDRNOTAVAIL;
602 memcpy(&b->sockaddr, result->ai_addr, result->ai_addrlen);
603 b->sockaddr_size = result->ai_addrlen;
605 freeaddrinfo(result);
610 static int parse_exec_address(sd_bus *b, const char **p, char **guid) {
612 unsigned n_argv = 0, j;
614 size_t allocated = 0;
622 while (**p != 0 && **p != ';') {
623 r = parse_address_key(p, "guid", guid);
629 r = parse_address_key(p, "path", &path);
635 if (startswith(*p, "argv")) {
639 ul = strtoul(*p + 4, (char**) p, 10);
640 if (errno > 0 || **p != '=' || ul > 256) {
648 if (!GREEDY_REALLOC0(argv, allocated, ul + 2)) {
656 r = parse_address_key(p, NULL, argv + ul);
671 /* Make sure there are no holes in the array, with the
672 * exception of argv[0] */
673 for (j = 1; j < n_argv; j++)
679 if (argv && argv[0] == NULL) {
680 argv[0] = strdup(path);
692 for (j = 0; j < n_argv; j++)
700 static int parse_kernel_address(sd_bus *b, const char **p, char **guid) {
701 _cleanup_free_ char *path = NULL;
709 while (**p != 0 && **p != ';') {
710 r = parse_address_key(p, "guid", guid);
716 r = parse_address_key(p, "path", &path);
735 static int parse_container_unix_address(sd_bus *b, const char **p, char **guid) {
736 _cleanup_free_ char *machine = NULL;
744 while (**p != 0 && **p != ';') {
745 r = parse_address_key(p, "guid", guid);
751 r = parse_address_key(p, "machine", &machine);
763 if (!filename_is_safe(machine))
767 b->machine = machine;
770 b->sockaddr.un.sun_family = AF_UNIX;
771 strncpy(b->sockaddr.un.sun_path, "/var/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
772 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + sizeof("/var/run/dbus/system_bus_socket") - 1;
777 static int parse_container_kernel_address(sd_bus *b, const char **p, char **guid) {
778 _cleanup_free_ char *machine = NULL;
786 while (**p != 0 && **p != ';') {
787 r = parse_address_key(p, "guid", guid);
793 r = parse_address_key(p, "machine", &machine);
805 if (!filename_is_safe(machine))
809 b->machine = machine;
813 b->kernel = strdup("/dev/kdbus/0-system/bus");
820 static void bus_reset_parsed_address(sd_bus *b) {
824 b->sockaddr_size = 0;
825 strv_free(b->exec_argv);
829 b->server_id = SD_ID128_NULL;
836 static int bus_parse_next_address(sd_bus *b) {
837 _cleanup_free_ char *guid = NULL;
845 if (b->address[b->address_index] == 0)
848 bus_reset_parsed_address(b);
850 a = b->address + b->address_index;
859 if (startswith(a, "unix:")) {
862 r = parse_unix_address(b, &a, &guid);
867 } else if (startswith(a, "tcp:")) {
870 r = parse_tcp_address(b, &a, &guid);
876 } else if (startswith(a, "unixexec:")) {
879 r = parse_exec_address(b, &a, &guid);
885 } else if (startswith(a, "kernel:")) {
888 r = parse_kernel_address(b, &a, &guid);
893 } else if (startswith(a, "x-container-unix:")) {
896 r = parse_container_unix_address(b, &a, &guid);
901 } else if (startswith(a, "x-container-kernel:")) {
904 r = parse_container_kernel_address(b, &a, &guid);
917 r = sd_id128_from_string(guid, &b->server_id);
922 b->address_index = a - b->address;
926 static int bus_start_address(sd_bus *b) {
932 bool skipped = false;
937 r = bus_socket_exec(b);
938 else if (b->machine && b->kernel)
939 r = bus_container_connect_kernel(b);
940 else if (b->machine && b->sockaddr.sa.sa_family != AF_UNSPEC)
941 r = bus_container_connect_socket(b);
943 r = bus_kernel_connect(b);
944 else if (b->sockaddr.sa.sa_family != AF_UNSPEC)
945 r = bus_socket_connect(b);
951 r = attach_io_events(b);
956 b->last_connect_error = -r;
959 r = bus_parse_next_address(b);
963 return b->last_connect_error ? -b->last_connect_error : -ECONNREFUSED;
967 int bus_next_address(sd_bus *b) {
970 bus_reset_parsed_address(b);
971 return bus_start_address(b);
974 static int bus_start_fd(sd_bus *b) {
979 assert(b->input_fd >= 0);
980 assert(b->output_fd >= 0);
982 r = fd_nonblock(b->input_fd, true);
986 r = fd_cloexec(b->input_fd, true);
990 if (b->input_fd != b->output_fd) {
991 r = fd_nonblock(b->output_fd, true);
995 r = fd_cloexec(b->output_fd, true);
1000 if (fstat(b->input_fd, &st) < 0)
1003 if (S_ISCHR(b->input_fd))
1004 return bus_kernel_take_fd(b);
1006 return bus_socket_take_fd(b);
1009 _public_ int sd_bus_start(sd_bus *bus) {
1012 assert_return(bus, -EINVAL);
1013 assert_return(bus->state == BUS_UNSET, -EPERM);
1014 assert_return(!bus_pid_changed(bus), -ECHILD);
1016 bus->state = BUS_OPENING;
1018 if (bus->is_server && bus->bus_client)
1021 if (bus->input_fd >= 0)
1022 r = bus_start_fd(bus);
1023 else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->kernel || bus->machine)
1024 r = bus_start_address(bus);
1031 return bus_send_hello(bus);
1034 _public_ int sd_bus_open_system(sd_bus **ret) {
1039 assert_return(ret, -EINVAL);
1045 e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1047 r = sd_bus_set_address(b, e);
1050 r = sd_bus_set_address(b, "kernel:path=/dev/kdbus/0-system/bus;unix:path=/run/dbus/system_bus_socket");
1052 r = sd_bus_set_address(b, "unix:path=/run/dbus/system_bus_socket");
1058 b->bus_client = true;
1060 /* Let's do per-method access control on the system bus. We
1061 * need the caller's UID and capability set for that. */
1063 b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1065 r = sd_bus_start(b);
1077 _public_ int sd_bus_open_user(sd_bus **ret) {
1082 assert_return(ret, -EINVAL);
1088 e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
1090 r = sd_bus_set_address(b, e);
1094 e = secure_getenv("XDG_RUNTIME_DIR");
1096 _cleanup_free_ char *ee = NULL;
1098 ee = bus_address_escape(e);
1105 asprintf(&b->address, "kernel:path=/dev/kdbus/%lu-user/bus;unix:path=%s/bus", (unsigned long) getuid(), ee);
1107 b->address = strjoin("unix:path=", ee, "/bus", NULL);
1111 asprintf(&b->address, "kernel:path=/dev/kdbus/%lu-user/bus", (unsigned long) getuid());
1113 return -ECONNREFUSED;
1123 b->bus_client = true;
1125 /* We don't do any per-method access control on the user
1129 r = sd_bus_start(b);
1141 _public_ int sd_bus_open_system_remote(const char *host, sd_bus **ret) {
1142 _cleanup_free_ char *e = NULL;
1147 assert_return(host, -EINVAL);
1148 assert_return(ret, -EINVAL);
1150 e = bus_address_escape(host);
1154 p = strjoin("unixexec:path=ssh,argv1=-xT,argv2=", e, ",argv3=systemd-stdio-bridge", NULL);
1158 r = sd_bus_new(&bus);
1165 bus->bus_client = true;
1167 r = sd_bus_start(bus);
1177 _public_ int sd_bus_open_system_container(const char *machine, sd_bus **ret) {
1178 _cleanup_free_ char *e = NULL;
1183 assert_return(machine, -EINVAL);
1184 assert_return(ret, -EINVAL);
1185 assert_return(filename_is_safe(machine), -EINVAL);
1187 e = bus_address_escape(machine);
1192 p = strjoin("x-container-kernel:machine=", e, ";x-container-unix:machine=", e, NULL);
1194 p = strjoin("x-container-unix:machine=", e, NULL);
1199 r = sd_bus_new(&bus);
1206 bus->bus_client = true;
1208 r = sd_bus_start(bus);
1218 _public_ void sd_bus_close(sd_bus *bus) {
1222 if (bus->state == BUS_CLOSED)
1224 if (bus_pid_changed(bus))
1227 bus->state = BUS_CLOSED;
1229 sd_bus_detach_event(bus);
1231 /* Drop all queued messages so that they drop references to
1232 * the bus object and the bus may be freed */
1233 bus_reset_queues(bus);
1235 if (!bus->is_kernel)
1238 /* We'll leave the fd open in case this is a kernel bus, since
1239 * there might still be memblocks around that reference this
1240 * bus, and they might need to invoke the * KDBUS_CMD_FREE
1241 * ioctl on the fd when they are freed. */
1244 static void bus_enter_closing(sd_bus *bus) {
1247 if (bus->state != BUS_OPENING &&
1248 bus->state != BUS_AUTHENTICATING &&
1249 bus->state != BUS_HELLO &&
1250 bus->state != BUS_RUNNING)
1253 bus->state = BUS_CLOSING;
1256 _public_ sd_bus *sd_bus_ref(sd_bus *bus) {
1257 assert_return(bus, NULL);
1259 assert_se(REFCNT_INC(bus->n_ref) >= 2);
1264 _public_ sd_bus *sd_bus_unref(sd_bus *bus) {
1269 if (REFCNT_DEC(bus->n_ref) <= 0)
1275 _public_ int sd_bus_is_open(sd_bus *bus) {
1277 assert_return(bus, -EINVAL);
1278 assert_return(!bus_pid_changed(bus), -ECHILD);
1280 return BUS_IS_OPEN(bus->state);
1283 _public_ int sd_bus_can_send(sd_bus *bus, char type) {
1286 assert_return(bus, -EINVAL);
1287 assert_return(bus->state != BUS_UNSET, -ENOTCONN);
1288 assert_return(!bus_pid_changed(bus), -ECHILD);
1290 if (type == SD_BUS_TYPE_UNIX_FD) {
1291 if (!(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD))
1294 r = bus_ensure_running(bus);
1298 return bus->can_fds;
1301 return bus_type_is_valid(type);
1304 _public_ int sd_bus_get_server_id(sd_bus *bus, sd_id128_t *server_id) {
1307 assert_return(bus, -EINVAL);
1308 assert_return(server_id, -EINVAL);
1309 assert_return(!bus_pid_changed(bus), -ECHILD);
1311 r = bus_ensure_running(bus);
1315 *server_id = bus->server_id;
1319 static int bus_seal_message(sd_bus *b, sd_bus_message *m, usec_t timeout) {
1324 /* If we copy the same message to multiple
1325 * destinations, avoid using the same serial
1327 b->serial = MAX(b->serial, BUS_MESSAGE_SERIAL(m));
1332 timeout = BUS_DEFAULT_TIMEOUT;
1334 return bus_message_seal(m, ++b->serial, timeout);
1337 static int bus_remarshal_message(sd_bus *b, sd_bus_message **m) {
1340 /* Do packet version and endianess already match? */
1341 if ((b->message_version == 0 || b->message_version == (*m)->header->version) &&
1342 (b->message_endian == 0 || b->message_endian == (*m)->header->endian))
1345 /* No? Then remarshal! */
1346 return bus_message_remarshal(b, m);
1349 int bus_seal_synthetic_message(sd_bus *b, sd_bus_message *m) {
1353 /* The bus specification says the serial number cannot be 0,
1354 * hence let's fill something in for synthetic messages. Since
1355 * synthetic messages might have a fake sender and we don't
1356 * want to interfere with the real sender's serial numbers we
1357 * pick a fixed, artifical one. We use (uint32_t) -1 rather
1358 * than (uint64_t) -1 since dbus1 only had 32bit identifiers,
1359 * even though kdbus can do 64bit. */
1361 return bus_message_seal(m, 0xFFFFFFFFULL, 0);
1364 static int bus_write_message(sd_bus *bus, sd_bus_message *message, size_t *idx) {
1369 return bus_kernel_write_message(bus, message);
1371 return bus_socket_write_message(bus, message, idx);
1374 static int dispatch_wqueue(sd_bus *bus) {
1378 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1380 while (bus->wqueue_size > 0) {
1382 r = bus_write_message(bus, bus->wqueue[0], &bus->windex);
1386 /* Didn't do anything this time */
1388 else if (bus->is_kernel || bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
1389 /* Fully written. Let's drop the entry from
1392 * This isn't particularly optimized, but
1393 * well, this is supposed to be our worst-case
1394 * buffer only, and the socket buffer is
1395 * supposed to be our primary buffer, and if
1396 * it got full, then all bets are off
1399 sd_bus_message_unref(bus->wqueue[0]);
1400 bus->wqueue_size --;
1401 memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
1411 static int bus_read_message(sd_bus *bus) {
1415 return bus_kernel_read_message(bus);
1417 return bus_socket_read_message(bus);
1420 int bus_rqueue_make_room(sd_bus *bus) {
1423 if (bus->rqueue_size >= BUS_RQUEUE_MAX)
1426 if (!GREEDY_REALLOC(bus->rqueue, bus->rqueue_allocated, bus->rqueue_size + 1))
1432 static int dispatch_rqueue(sd_bus *bus, sd_bus_message **m) {
1437 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1440 if (bus->rqueue_size > 0) {
1441 /* Dispatch a queued message */
1443 *m = bus->rqueue[0];
1444 bus->rqueue_size --;
1445 memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
1449 /* Try to read a new message */
1450 r = bus_read_message(bus);
1460 _public_ int sd_bus_send(sd_bus *bus, sd_bus_message *_m, uint64_t *serial) {
1461 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1464 assert_return(bus, -EINVAL);
1465 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1466 assert_return(m, -EINVAL);
1467 assert_return(!bus_pid_changed(bus), -ECHILD);
1470 r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
1477 /* If the serial number isn't kept, then we know that no reply
1479 if (!serial && !m->sealed)
1480 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1482 r = bus_seal_message(bus, m, 0);
1486 /* Remarshall if we have to. This will possible unref the
1487 * message and place a replacement in m */
1488 r = bus_remarshal_message(bus, &m);
1492 /* If this is a reply and no reply was requested, then let's
1493 * suppress this, if we can */
1494 if (m->dont_send && !serial)
1497 if ((bus->state == BUS_RUNNING || bus->state == BUS_HELLO) && bus->wqueue_size <= 0) {
1500 r = bus_write_message(bus, m, &idx);
1502 if (r == -EPIPE || r == -ENOTCONN || r == -ESHUTDOWN)
1503 bus_enter_closing(bus);
1506 } else if (!bus->is_kernel && idx < BUS_MESSAGE_SIZE(m)) {
1507 /* Wasn't fully written. So let's remember how
1508 * much was written. Note that the first entry
1509 * of the wqueue array is always allocated so
1510 * that we always can remember how much was
1512 bus->wqueue[0] = sd_bus_message_ref(m);
1513 bus->wqueue_size = 1;
1517 /* Just append it to the queue. */
1519 if (bus->wqueue_size >= BUS_WQUEUE_MAX)
1522 if (!GREEDY_REALLOC(bus->wqueue, bus->wqueue_allocated, bus->wqueue_size + 1))
1525 bus->wqueue[bus->wqueue_size ++] = sd_bus_message_ref(m);
1529 *serial = BUS_MESSAGE_SERIAL(m);
1534 _public_ int sd_bus_send_to(sd_bus *bus, sd_bus_message *m, const char *destination, uint64_t *serial) {
1537 assert_return(bus, -EINVAL);
1538 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1539 assert_return(m, -EINVAL);
1540 assert_return(!bus_pid_changed(bus), -ECHILD);
1542 if (!streq_ptr(m->destination, destination)) {
1547 r = sd_bus_message_set_destination(m, destination);
1552 return sd_bus_send(bus, m, serial);
1555 static usec_t calc_elapse(uint64_t usec) {
1556 if (usec == (uint64_t) -1)
1559 return now(CLOCK_MONOTONIC) + usec;
1562 static int timeout_compare(const void *a, const void *b) {
1563 const struct reply_callback *x = a, *y = b;
1565 if (x->timeout != 0 && y->timeout == 0)
1568 if (x->timeout == 0 && y->timeout != 0)
1571 if (x->timeout < y->timeout)
1574 if (x->timeout > y->timeout)
1580 _public_ int sd_bus_call_async(
1583 sd_bus_message_handler_t callback,
1588 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1589 struct reply_callback *c;
1592 assert_return(bus, -EINVAL);
1593 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1594 assert_return(m, -EINVAL);
1595 assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1596 assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1597 assert_return(callback, -EINVAL);
1598 assert_return(!bus_pid_changed(bus), -ECHILD);
1600 r = hashmap_ensure_allocated(&bus->reply_callbacks, uint64_hash_func, uint64_compare_func);
1604 r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
1608 r = bus_seal_message(bus, m, usec);
1612 r = bus_remarshal_message(bus, &m);
1616 c = new0(struct reply_callback, 1);
1620 c->callback = callback;
1621 c->userdata = userdata;
1622 c->serial = BUS_MESSAGE_SERIAL(m);
1623 c->timeout = calc_elapse(m->timeout);
1625 r = hashmap_put(bus->reply_callbacks, &c->serial, c);
1631 if (c->timeout != 0) {
1632 r = prioq_put(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1635 sd_bus_call_async_cancel(bus, c->serial);
1640 r = sd_bus_send(bus, m, serial);
1642 sd_bus_call_async_cancel(bus, c->serial);
1649 _public_ int sd_bus_call_async_cancel(sd_bus *bus, uint64_t serial) {
1650 struct reply_callback *c;
1652 assert_return(bus, -EINVAL);
1653 assert_return(serial != 0, -EINVAL);
1654 assert_return(!bus_pid_changed(bus), -ECHILD);
1656 c = hashmap_remove(bus->reply_callbacks, &serial);
1660 if (c->timeout != 0)
1661 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1667 int bus_ensure_running(sd_bus *bus) {
1672 if (bus->state == BUS_UNSET || bus->state == BUS_CLOSED || bus->state == BUS_CLOSING)
1674 if (bus->state == BUS_RUNNING)
1678 r = sd_bus_process(bus, NULL);
1681 if (bus->state == BUS_RUNNING)
1686 r = sd_bus_wait(bus, (uint64_t) -1);
1692 _public_ int sd_bus_call(
1696 sd_bus_error *error,
1697 sd_bus_message **reply) {
1699 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1705 assert_return(bus, -EINVAL);
1706 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1707 assert_return(m, -EINVAL);
1708 assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1709 assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1710 assert_return(!bus_error_is_dirty(error), -EINVAL);
1711 assert_return(!bus_pid_changed(bus), -ECHILD);
1713 r = bus_ensure_running(bus);
1717 i = bus->rqueue_size;
1719 r = bus_seal_message(bus, m, usec);
1723 r = bus_remarshal_message(bus, &m);
1727 r = sd_bus_send(bus, m, &serial);
1731 timeout = calc_elapse(m->timeout);
1736 while (i < bus->rqueue_size) {
1737 sd_bus_message *incoming = NULL;
1739 incoming = bus->rqueue[i];
1741 if (incoming->reply_serial == serial) {
1742 /* Found a match! */
1744 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1747 if (incoming->header->type == SD_BUS_MESSAGE_METHOD_RETURN) {
1752 sd_bus_message_unref(incoming);
1755 } else if (incoming->header->type == SD_BUS_MESSAGE_METHOD_ERROR)
1756 r = sd_bus_error_copy(error, &incoming->error);
1760 sd_bus_message_unref(incoming);
1763 } else if (incoming->header->serial == serial &&
1766 streq(bus->unique_name, incoming->sender)) {
1768 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1771 /* Our own message? Somebody is trying
1772 * to send its own client a message,
1773 * let's not dead-lock, let's fail
1776 sd_bus_message_unref(incoming);
1780 /* Try to read more, right-away */
1784 r = bus_read_message(bus);
1786 if (r == -EPIPE || r == -ENOTCONN || r == -ESHUTDOWN)
1787 bus_enter_closing(bus);
1797 n = now(CLOCK_MONOTONIC);
1803 left = (uint64_t) -1;
1805 r = bus_poll(bus, true, left);
1811 r = dispatch_wqueue(bus);
1813 if (r == -EPIPE || r == -ENOTCONN || r == -ESHUTDOWN)
1814 bus_enter_closing(bus);
1821 _public_ int sd_bus_get_fd(sd_bus *bus) {
1823 assert_return(bus, -EINVAL);
1824 assert_return(bus->input_fd == bus->output_fd, -EPERM);
1825 assert_return(!bus_pid_changed(bus), -ECHILD);
1827 return bus->input_fd;
1830 _public_ int sd_bus_get_events(sd_bus *bus) {
1833 assert_return(bus, -EINVAL);
1834 assert_return(BUS_IS_OPEN(bus->state) || bus->state == BUS_CLOSING, -ENOTCONN);
1835 assert_return(!bus_pid_changed(bus), -ECHILD);
1837 if (bus->state == BUS_OPENING)
1839 else if (bus->state == BUS_AUTHENTICATING) {
1841 if (bus_socket_auth_needs_write(bus))
1846 } else if (bus->state == BUS_RUNNING || bus->state == BUS_HELLO) {
1847 if (bus->rqueue_size <= 0)
1849 if (bus->wqueue_size > 0)
1856 _public_ int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
1857 struct reply_callback *c;
1859 assert_return(bus, -EINVAL);
1860 assert_return(timeout_usec, -EINVAL);
1861 assert_return(BUS_IS_OPEN(bus->state) || bus->state == BUS_CLOSING, -ENOTCONN);
1862 assert_return(!bus_pid_changed(bus), -ECHILD);
1864 if (bus->state == BUS_CLOSING) {
1869 if (bus->state == BUS_AUTHENTICATING) {
1870 *timeout_usec = bus->auth_timeout;
1874 if (bus->state != BUS_RUNNING && bus->state != BUS_HELLO) {
1875 *timeout_usec = (uint64_t) -1;
1879 if (bus->rqueue_size > 0) {
1884 c = prioq_peek(bus->reply_callbacks_prioq);
1886 *timeout_usec = (uint64_t) -1;
1890 *timeout_usec = c->timeout;
1894 static int process_timeout(sd_bus *bus) {
1895 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
1896 _cleanup_bus_message_unref_ sd_bus_message* m = NULL;
1897 struct reply_callback *c;
1903 c = prioq_peek(bus->reply_callbacks_prioq);
1907 n = now(CLOCK_MONOTONIC);
1911 r = bus_message_new_synthetic_error(
1914 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
1919 m->sender = "org.freedesktop.DBus";
1921 r = bus_seal_synthetic_message(bus, m);
1925 assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
1926 hashmap_remove(bus->reply_callbacks, &c->serial);
1929 bus->iteration_counter ++;
1931 r = c->callback(bus, m, c->userdata, &error_buffer);
1932 r = bus_maybe_reply_error(m, r, &error_buffer);
1935 bus->current = NULL;
1940 static int process_hello(sd_bus *bus, sd_bus_message *m) {
1944 if (bus->state != BUS_HELLO)
1947 /* Let's make sure the first message on the bus is the HELLO
1948 * reply. But note that we don't actually parse the message
1949 * here (we leave that to the usual handling), we just verify
1950 * we don't let any earlier msg through. */
1952 if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
1953 m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
1956 if (m->reply_serial != bus->hello_serial)
1962 static int process_reply(sd_bus *bus, sd_bus_message *m) {
1963 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
1964 struct reply_callback *c;
1970 if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
1971 m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
1974 c = hashmap_remove(bus->reply_callbacks, &m->reply_serial);
1978 if (c->timeout != 0)
1979 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1981 r = sd_bus_message_rewind(m, true);
1985 r = c->callback(bus, m, c->userdata, &error_buffer);
1986 r = bus_maybe_reply_error(m, r, &error_buffer);
1992 static int process_filter(sd_bus *bus, sd_bus_message *m) {
1993 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
1994 struct filter_callback *l;
2001 bus->filter_callbacks_modified = false;
2003 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
2005 if (bus->filter_callbacks_modified)
2008 /* Don't run this more than once per iteration */
2009 if (l->last_iteration == bus->iteration_counter)
2012 l->last_iteration = bus->iteration_counter;
2014 r = sd_bus_message_rewind(m, true);
2018 r = l->callback(bus, m, l->userdata, &error_buffer);
2019 r = bus_maybe_reply_error(m, r, &error_buffer);
2025 } while (bus->filter_callbacks_modified);
2030 static int process_match(sd_bus *bus, sd_bus_message *m) {
2037 bus->match_callbacks_modified = false;
2039 r = bus_match_run(bus, &bus->match_callbacks, m);
2043 } while (bus->match_callbacks_modified);
2048 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
2049 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2055 if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2058 if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2061 if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2064 if (streq_ptr(m->member, "Ping"))
2065 r = sd_bus_message_new_method_return(m, &reply);
2066 else if (streq_ptr(m->member, "GetMachineId")) {
2070 r = sd_id128_get_machine(&id);
2074 r = sd_bus_message_new_method_return(m, &reply);
2078 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2080 r = sd_bus_message_new_method_errorf(
2082 SD_BUS_ERROR_UNKNOWN_METHOD,
2083 "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2089 r = sd_bus_send(bus, reply, NULL);
2096 static int process_message(sd_bus *bus, sd_bus_message *m) {
2103 bus->iteration_counter++;
2105 log_debug("Got message sender=%s object=%s interface=%s member=%s",
2106 strna(sd_bus_message_get_sender(m)),
2107 strna(sd_bus_message_get_path(m)),
2108 strna(sd_bus_message_get_interface(m)),
2109 strna(sd_bus_message_get_member(m)));
2111 r = process_hello(bus, m);
2115 r = process_reply(bus, m);
2119 r = process_filter(bus, m);
2123 r = process_match(bus, m);
2127 r = process_builtin(bus, m);
2131 r = bus_process_object(bus, m);
2134 bus->current = NULL;
2138 static int process_running(sd_bus *bus, sd_bus_message **ret) {
2139 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2143 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
2145 r = process_timeout(bus);
2149 r = dispatch_wqueue(bus);
2153 r = dispatch_rqueue(bus, &m);
2159 r = process_message(bus, m);
2164 r = sd_bus_message_rewind(m, true);
2173 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2175 log_debug("Unprocessed message call sender=%s object=%s interface=%s member=%s",
2176 strna(sd_bus_message_get_sender(m)),
2177 strna(sd_bus_message_get_path(m)),
2178 strna(sd_bus_message_get_interface(m)),
2179 strna(sd_bus_message_get_member(m)));
2181 r = sd_bus_reply_method_errorf(
2183 SD_BUS_ERROR_UNKNOWN_OBJECT,
2184 "Unknown object '%s'.", m->path);
2198 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2199 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2200 struct reply_callback *c;
2204 assert(bus->state == BUS_CLOSING);
2206 c = hashmap_first(bus->reply_callbacks);
2208 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2210 /* First, fail all outstanding method calls */
2211 r = bus_message_new_synthetic_error(
2214 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2219 r = bus_seal_synthetic_message(bus, m);
2223 if (c->timeout != 0)
2224 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2226 hashmap_remove(bus->reply_callbacks, &c->serial);
2229 bus->iteration_counter++;
2231 r = c->callback(bus, m, c->userdata, &error_buffer);
2232 r = bus_maybe_reply_error(m, r, &error_buffer);
2238 /* Then, synthesize a Disconnected message */
2239 r = sd_bus_message_new_signal(
2241 "/org/freedesktop/DBus/Local",
2242 "org.freedesktop.DBus.Local",
2248 m->sender = "org.freedesktop.DBus.Local";
2250 r = bus_seal_synthetic_message(bus, m);
2257 bus->iteration_counter++;
2259 r = process_filter(bus, m);
2263 r = process_match(bus, m);
2275 bus->current = NULL;
2279 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2280 BUS_DONT_DESTROY(bus);
2283 /* Returns 0 when we didn't do anything. This should cause the
2284 * caller to invoke sd_bus_wait() before returning the next
2285 * time. Returns > 0 when we did something, which possibly
2286 * means *ret is filled in with an unprocessed message. */
2288 assert_return(bus, -EINVAL);
2289 assert_return(!bus_pid_changed(bus), -ECHILD);
2291 /* We don't allow recursively invoking sd_bus_process(). */
2292 assert_return(!bus->current, -EBUSY);
2294 switch (bus->state) {
2303 r = bus_socket_process_opening(bus);
2304 if (r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2305 bus_enter_closing(bus);
2313 case BUS_AUTHENTICATING:
2314 r = bus_socket_process_authenticating(bus);
2315 if (r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2316 bus_enter_closing(bus);
2328 r = process_running(bus, ret);
2329 if (r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2330 bus_enter_closing(bus);
2340 return process_closing(bus, ret);
2343 assert_not_reached("Unknown state");
2346 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2347 struct pollfd p[2] = {};
2350 usec_t m = (usec_t) -1;
2354 if (bus->state == BUS_CLOSING)
2357 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2359 e = sd_bus_get_events(bus);
2364 /* The caller really needs some more data, he doesn't
2365 * care about what's already read, or any timeouts
2370 /* The caller wants to process if there's something to
2371 * process, but doesn't care otherwise */
2373 r = sd_bus_get_timeout(bus, &until);
2378 nw = now(CLOCK_MONOTONIC);
2379 m = until > nw ? until - nw : 0;
2383 if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
2386 p[0].fd = bus->input_fd;
2387 if (bus->output_fd == bus->input_fd) {
2391 p[0].events = e & POLLIN;
2392 p[1].fd = bus->output_fd;
2393 p[1].events = e & POLLOUT;
2397 r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
2401 return r > 0 ? 1 : 0;
2404 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
2406 assert_return(bus, -EINVAL);
2407 assert_return(!bus_pid_changed(bus), -ECHILD);
2409 if (bus->state == BUS_CLOSING)
2412 assert_return(BUS_IS_OPEN(bus->state) , -ENOTCONN);
2414 if (bus->rqueue_size > 0)
2417 return bus_poll(bus, false, timeout_usec);
2420 _public_ int sd_bus_flush(sd_bus *bus) {
2423 assert_return(bus, -EINVAL);
2424 assert_return(!bus_pid_changed(bus), -ECHILD);
2426 if (bus->state == BUS_CLOSING)
2429 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2431 r = bus_ensure_running(bus);
2435 if (bus->wqueue_size <= 0)
2439 r = dispatch_wqueue(bus);
2441 if (r == -EPIPE || r == -ENOTCONN || r == -ESHUTDOWN)
2442 bus_enter_closing(bus);
2447 if (bus->wqueue_size <= 0)
2450 r = bus_poll(bus, false, (uint64_t) -1);
2456 _public_ int sd_bus_add_filter(sd_bus *bus,
2457 sd_bus_message_handler_t callback,
2460 struct filter_callback *f;
2462 assert_return(bus, -EINVAL);
2463 assert_return(callback, -EINVAL);
2464 assert_return(!bus_pid_changed(bus), -ECHILD);
2466 f = new0(struct filter_callback, 1);
2469 f->callback = callback;
2470 f->userdata = userdata;
2472 bus->filter_callbacks_modified = true;
2473 LIST_PREPEND(callbacks, bus->filter_callbacks, f);
2477 _public_ int sd_bus_remove_filter(sd_bus *bus,
2478 sd_bus_message_handler_t callback,
2481 struct filter_callback *f;
2483 assert_return(bus, -EINVAL);
2484 assert_return(callback, -EINVAL);
2485 assert_return(!bus_pid_changed(bus), -ECHILD);
2487 LIST_FOREACH(callbacks, f, bus->filter_callbacks) {
2488 if (f->callback == callback && f->userdata == userdata) {
2489 bus->filter_callbacks_modified = true;
2490 LIST_REMOVE(callbacks, bus->filter_callbacks, f);
2499 _public_ int sd_bus_add_match(sd_bus *bus,
2501 sd_bus_message_handler_t callback,
2504 struct bus_match_component *components = NULL;
2505 unsigned n_components = 0;
2506 uint64_t cookie = 0;
2509 assert_return(bus, -EINVAL);
2510 assert_return(match, -EINVAL);
2511 assert_return(!bus_pid_changed(bus), -ECHILD);
2513 r = bus_match_parse(match, &components, &n_components);
2517 if (bus->bus_client) {
2518 cookie = ++bus->match_cookie;
2520 r = bus_add_match_internal(bus, match, components, n_components, cookie);
2525 bus->match_callbacks_modified = true;
2526 r = bus_match_add(&bus->match_callbacks, components, n_components, callback, userdata, cookie, NULL);
2528 if (bus->bus_client)
2529 bus_remove_match_internal(bus, match, cookie);
2533 bus_match_parse_free(components, n_components);
2537 _public_ int sd_bus_remove_match(sd_bus *bus,
2539 sd_bus_message_handler_t callback,
2542 struct bus_match_component *components = NULL;
2543 unsigned n_components = 0;
2545 uint64_t cookie = 0;
2547 assert_return(bus, -EINVAL);
2548 assert_return(match, -EINVAL);
2549 assert_return(!bus_pid_changed(bus), -ECHILD);
2551 r = bus_match_parse(match, &components, &n_components);
2555 bus->match_callbacks_modified = true;
2556 r = bus_match_remove(&bus->match_callbacks, components, n_components, callback, userdata, &cookie);
2558 if (bus->bus_client)
2559 q = bus_remove_match_internal(bus, match, cookie);
2561 bus_match_parse_free(components, n_components);
2563 return r < 0 ? r : q;
2566 bool bus_pid_changed(sd_bus *bus) {
2569 /* We don't support people creating a bus connection and
2570 * keeping it around over a fork(). Let's complain. */
2572 return bus->original_pid != getpid();
2575 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2576 sd_bus *bus = userdata;
2581 r = sd_bus_process(bus, NULL);
2588 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
2589 sd_bus *bus = userdata;
2594 r = sd_bus_process(bus, NULL);
2601 static int prepare_callback(sd_event_source *s, void *userdata) {
2602 sd_bus *bus = userdata;
2609 e = sd_bus_get_events(bus);
2613 if (bus->output_fd != bus->input_fd) {
2615 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
2619 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
2623 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
2628 r = sd_bus_get_timeout(bus, &until);
2634 j = sd_event_source_set_time(bus->time_event_source, until);
2639 r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
2646 static int quit_callback(sd_event_source *event, void *userdata) {
2647 sd_bus *bus = userdata;
2656 static int attach_io_events(sd_bus *bus) {
2661 if (bus->input_fd < 0)
2667 if (!bus->input_io_event_source) {
2668 r = sd_event_add_io(bus->event, bus->input_fd, 0, io_callback, bus, &bus->input_io_event_source);
2672 r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
2676 r = sd_event_source_set_priority(bus->input_io_event_source, bus->event_priority);
2678 r = sd_event_source_set_io_fd(bus->input_io_event_source, bus->input_fd);
2683 if (bus->output_fd != bus->input_fd) {
2684 assert(bus->output_fd >= 0);
2686 if (!bus->output_io_event_source) {
2687 r = sd_event_add_io(bus->event, bus->output_fd, 0, io_callback, bus, &bus->output_io_event_source);
2691 r = sd_event_source_set_priority(bus->output_io_event_source, bus->event_priority);
2693 r = sd_event_source_set_io_fd(bus->output_io_event_source, bus->output_fd);
2702 static void detach_io_events(sd_bus *bus) {
2705 if (bus->input_io_event_source) {
2706 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
2707 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
2710 if (bus->output_io_event_source) {
2711 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
2712 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
2716 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
2719 assert_return(bus, -EINVAL);
2720 assert_return(!bus->event, -EBUSY);
2722 assert(!bus->input_io_event_source);
2723 assert(!bus->output_io_event_source);
2724 assert(!bus->time_event_source);
2727 bus->event = sd_event_ref(event);
2729 r = sd_event_default(&bus->event);
2734 bus->event_priority = priority;
2736 r = sd_event_add_monotonic(bus->event, 0, 0, time_callback, bus, &bus->time_event_source);
2740 r = sd_event_source_set_priority(bus->time_event_source, priority);
2744 r = sd_event_add_exit(bus->event, quit_callback, bus, &bus->quit_event_source);
2748 r = attach_io_events(bus);
2755 sd_bus_detach_event(bus);
2759 _public_ int sd_bus_detach_event(sd_bus *bus) {
2760 assert_return(bus, -EINVAL);
2765 detach_io_events(bus);
2767 if (bus->time_event_source) {
2768 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
2769 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
2772 if (bus->quit_event_source) {
2773 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
2774 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
2778 bus->event = sd_event_unref(bus->event);
2783 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
2784 assert_return(bus, NULL);
2789 _public_ sd_bus_message* sd_bus_get_current(sd_bus *bus) {
2790 assert_return(bus, NULL);
2792 return bus->current;
2795 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
2800 assert(default_bus);
2803 return !!*default_bus;
2806 *ret = sd_bus_ref(*default_bus);
2814 b->default_bus_ptr = default_bus;
2822 _public_ int sd_bus_default_system(sd_bus **ret) {
2823 static thread_local sd_bus *default_system_bus = NULL;
2825 return bus_default(sd_bus_open_system, &default_system_bus, ret);
2828 _public_ int sd_bus_default_user(sd_bus **ret) {
2829 static thread_local sd_bus *default_user_bus = NULL;
2831 return bus_default(sd_bus_open_user, &default_user_bus, ret);
2834 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
2835 assert_return(b, -EINVAL);
2836 assert_return(tid, -EINVAL);
2837 assert_return(!bus_pid_changed(b), -ECHILD);
2845 return sd_event_get_tid(b->event, tid);
2850 _public_ char *sd_bus_label_escape(const char *s) {
2854 assert_return(s, NULL);
2856 /* Escapes all chars that D-Bus' object path cannot deal
2857 * with. Can be reversed with bus_path_unescape(). We special
2858 * case the empty string. */
2863 r = new(char, strlen(s)*3 + 1);
2867 for (f = s, t = r; *f; f++) {
2869 /* Escape everything that is not a-zA-Z0-9. We also
2870 * escape 0-9 if it's the first character */
2872 if (!(*f >= 'A' && *f <= 'Z') &&
2873 !(*f >= 'a' && *f <= 'z') &&
2874 !(f > s && *f >= '0' && *f <= '9')) {
2876 *(t++) = hexchar(*f >> 4);
2877 *(t++) = hexchar(*f);
2887 _public_ char *sd_bus_label_unescape(const char *f) {
2890 assert_return(f, NULL);
2892 /* Special case for the empty string */
2896 r = new(char, strlen(f) + 1);
2900 for (t = r; *f; f++) {
2905 if ((a = unhexchar(f[1])) < 0 ||
2906 (b = unhexchar(f[2])) < 0) {
2907 /* Invalid escape code, let's take it literal then */
2910 *(t++) = (char) ((a << 4) | b);
2922 _public_ int sd_bus_get_peer_creds(sd_bus *bus, uint64_t mask, sd_bus_creds **ret) {
2927 assert_return(bus, -EINVAL);
2928 assert_return(mask <= _SD_BUS_CREDS_ALL, -ENOTSUP);
2929 assert_return(ret, -EINVAL);
2930 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2931 assert_return(!bus_pid_changed(bus), -ECHILD);
2932 assert_return(!bus->is_kernel, -ENOTSUP);
2934 if (!bus->ucred_valid && !isempty(bus->label))
2937 c = bus_creds_new();
2941 if (bus->ucred_valid) {
2942 pid = c->pid = bus->ucred.pid;
2943 c->uid = bus->ucred.uid;
2944 c->gid = bus->ucred.gid;
2946 c->mask |= (SD_BUS_CREDS_UID | SD_BUS_CREDS_PID | SD_BUS_CREDS_GID) & mask;
2949 if (!isempty(bus->label) && (mask & SD_BUS_CREDS_SELINUX_CONTEXT)) {
2950 c->label = strdup(bus->label);
2952 sd_bus_creds_unref(c);
2956 c->mask |= SD_BUS_CREDS_SELINUX_CONTEXT;
2959 r = bus_creds_add_more(c, mask, pid, 0);
2967 _public_ int sd_bus_try_close(sd_bus *bus) {
2970 assert_return(bus, -EINVAL);
2971 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2972 assert_return(!bus_pid_changed(bus), -ECHILD);
2973 assert_return(bus->is_kernel, -ENOTSUP);
2975 if (bus->rqueue_size > 0)
2978 if (bus->wqueue_size > 0)
2981 r = bus_kernel_try_close(bus);