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/>.
38 #include "cgroup-util.h"
41 #include "bus-internal.h"
42 #include "bus-message.h"
44 #include "bus-socket.h"
45 #include "bus-kernel.h"
46 #include "bus-control.h"
47 #include "bus-introspect.h"
48 #include "bus-signature.h"
49 #include "bus-objects.h"
51 #include "bus-container.h"
52 #include "bus-protocol.h"
54 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec);
55 static int attach_io_events(sd_bus *b);
56 static void detach_io_events(sd_bus *b);
58 static void bus_close_fds(sd_bus *b) {
64 close_nointr_nofail(b->input_fd);
66 if (b->output_fd >= 0 && b->output_fd != b->input_fd)
67 close_nointr_nofail(b->output_fd);
69 b->input_fd = b->output_fd = -1;
72 static void bus_node_destroy(sd_bus *b, struct node *n) {
73 struct node_callback *c;
74 struct node_vtable *v;
75 struct node_enumerator *e;
83 bus_node_destroy(b, n->child);
85 while ((c = n->callbacks)) {
86 LIST_REMOVE(callbacks, n->callbacks, c);
90 while ((v = n->vtables)) {
91 LIST_REMOVE(vtables, n->vtables, v);
96 while ((e = n->enumerators)) {
97 LIST_REMOVE(enumerators, n->enumerators, e);
102 LIST_REMOVE(siblings, n->parent->child, n);
104 assert_se(hashmap_remove(b->nodes, n->path) == n);
109 static void bus_reset_queues(sd_bus *b) {
112 while (b->rqueue_size > 0)
113 sd_bus_message_unref(b->rqueue[--b->rqueue_size]);
117 b->rqueue_allocated = 0;
119 while (b->wqueue_size > 0)
120 sd_bus_message_unref(b->wqueue[--b->wqueue_size]);
124 b->wqueue_allocated = 0;
127 static void bus_free(sd_bus *b) {
128 struct filter_callback *f;
133 sd_bus_detach_event(b);
138 munmap(b->kdbus_buffer, KDBUS_POOL_SIZE);
141 free(b->unique_name);
142 free(b->auth_buffer);
147 free(b->cgroup_root);
148 free(b->connection_name);
151 strv_free(b->exec_argv);
153 close_many(b->fds, b->n_fds);
158 hashmap_free_free(b->reply_callbacks);
159 prioq_free(b->reply_callbacks_prioq);
161 while ((f = b->filter_callbacks)) {
162 LIST_REMOVE(callbacks, b->filter_callbacks, f);
166 bus_match_free(&b->match_callbacks);
168 hashmap_free_free(b->vtable_methods);
169 hashmap_free_free(b->vtable_properties);
171 while ((n = hashmap_first(b->nodes)))
172 bus_node_destroy(b, n);
174 hashmap_free(b->nodes);
176 bus_kernel_flush_memfd(b);
178 assert_se(pthread_mutex_destroy(&b->memfd_cache_mutex) == 0);
183 _public_ int sd_bus_new(sd_bus **ret) {
186 assert_return(ret, -EINVAL);
192 r->n_ref = REFCNT_INIT;
193 r->input_fd = r->output_fd = -1;
194 r->message_version = 1;
195 r->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
196 r->hello_flags |= KDBUS_HELLO_ACCEPT_FD;
197 r->attach_flags |= KDBUS_ATTACH_NAMES;
198 r->original_pid = getpid();
200 assert_se(pthread_mutex_init(&r->memfd_cache_mutex, NULL) == 0);
202 /* We guarantee that wqueue always has space for at least one
204 if (!GREEDY_REALLOC(r->wqueue, r->wqueue_allocated, 1)) {
213 _public_ int sd_bus_set_address(sd_bus *bus, const char *address) {
216 assert_return(bus, -EINVAL);
217 assert_return(bus->state == BUS_UNSET, -EPERM);
218 assert_return(address, -EINVAL);
219 assert_return(!bus_pid_changed(bus), -ECHILD);
231 _public_ int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd) {
232 assert_return(bus, -EINVAL);
233 assert_return(bus->state == BUS_UNSET, -EPERM);
234 assert_return(input_fd >= 0, -EINVAL);
235 assert_return(output_fd >= 0, -EINVAL);
236 assert_return(!bus_pid_changed(bus), -ECHILD);
238 bus->input_fd = input_fd;
239 bus->output_fd = output_fd;
243 _public_ int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]) {
246 assert_return(bus, -EINVAL);
247 assert_return(bus->state == BUS_UNSET, -EPERM);
248 assert_return(path, -EINVAL);
249 assert_return(!strv_isempty(argv), -EINVAL);
250 assert_return(!bus_pid_changed(bus), -ECHILD);
262 free(bus->exec_path);
263 strv_free(bus->exec_argv);
271 _public_ int sd_bus_set_bus_client(sd_bus *bus, int b) {
272 assert_return(bus, -EINVAL);
273 assert_return(bus->state == BUS_UNSET, -EPERM);
274 assert_return(!bus_pid_changed(bus), -ECHILD);
276 bus->bus_client = !!b;
280 _public_ int sd_bus_negotiate_fds(sd_bus *bus, int b) {
281 assert_return(bus, -EINVAL);
282 assert_return(bus->state == BUS_UNSET, -EPERM);
283 assert_return(!bus_pid_changed(bus), -ECHILD);
285 SET_FLAG(bus->hello_flags, KDBUS_HELLO_ACCEPT_FD, b);
289 _public_ int sd_bus_negotiate_timestamp(sd_bus *bus, int b) {
290 assert_return(bus, -EINVAL);
291 assert_return(bus->state == BUS_UNSET, -EPERM);
292 assert_return(!bus_pid_changed(bus), -ECHILD);
294 SET_FLAG(bus->attach_flags, KDBUS_ATTACH_TIMESTAMP, b);
298 _public_ int sd_bus_negotiate_creds(sd_bus *bus, uint64_t mask) {
299 assert_return(bus, -EINVAL);
300 assert_return(mask <= _SD_BUS_CREDS_ALL, -EINVAL);
301 assert_return(bus->state == BUS_UNSET, -EPERM);
302 assert_return(!bus_pid_changed(bus), -ECHILD);
304 /* The well knowns we need unconditionally, so that matches can work */
305 bus->creds_mask = mask | SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
307 return kdbus_translate_attach_flags(bus->creds_mask, &bus->creds_mask);
310 _public_ int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id) {
311 assert_return(bus, -EINVAL);
312 assert_return(b || sd_id128_equal(server_id, SD_ID128_NULL), -EINVAL);
313 assert_return(bus->state == BUS_UNSET, -EPERM);
314 assert_return(!bus_pid_changed(bus), -ECHILD);
316 bus->is_server = !!b;
317 bus->server_id = server_id;
321 _public_ int sd_bus_set_anonymous(sd_bus *bus, int b) {
322 assert_return(bus, -EINVAL);
323 assert_return(bus->state == BUS_UNSET, -EPERM);
324 assert_return(!bus_pid_changed(bus), -ECHILD);
326 bus->anonymous_auth = !!b;
330 _public_ int sd_bus_set_trusted(sd_bus *bus, int b) {
331 assert_return(bus, -EINVAL);
332 assert_return(bus->state == BUS_UNSET, -EPERM);
333 assert_return(!bus_pid_changed(bus), -ECHILD);
339 _public_ int sd_bus_set_name(sd_bus *bus, const char *name) {
342 assert_return(bus, -EINVAL);
343 assert_return(name, -EINVAL);
344 assert_return(bus->state == BUS_UNSET, -EPERM);
345 assert_return(!bus_pid_changed(bus), -ECHILD);
351 free(bus->connection_name);
352 bus->connection_name = n;
357 static int hello_callback(sd_bus *bus, sd_bus_message *reply, void *userdata, sd_bus_error *error) {
362 assert(bus->state == BUS_HELLO || bus->state == BUS_CLOSING);
365 r = sd_bus_message_get_errno(reply);
371 r = sd_bus_message_read(reply, "s", &s);
375 if (!service_name_is_valid(s) || s[0] != ':')
378 bus->unique_name = strdup(s);
379 if (!bus->unique_name)
382 if (bus->state == BUS_HELLO)
383 bus->state = BUS_RUNNING;
388 static int bus_send_hello(sd_bus *bus) {
389 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
394 if (!bus->bus_client || bus->is_kernel)
397 r = sd_bus_message_new_method_call(
399 "org.freedesktop.DBus",
400 "/org/freedesktop/DBus",
401 "org.freedesktop.DBus",
407 return sd_bus_call_async(bus, m, hello_callback, NULL, 0, &bus->hello_cookie);
410 int bus_start_running(sd_bus *bus) {
413 if (bus->bus_client && !bus->is_kernel) {
414 bus->state = BUS_HELLO;
418 bus->state = BUS_RUNNING;
422 static int parse_address_key(const char **p, const char *key, char **value) {
423 size_t l, n = 0, allocated = 0;
433 if (strncmp(*p, key, l) != 0)
446 while (*a != ';' && *a != ',' && *a != 0) {
464 c = (char) ((x << 4) | y);
471 if (!GREEDY_REALLOC(r, allocated, n + 2))
495 static void skip_address_key(const char **p) {
499 *p += strcspn(*p, ",");
505 static int parse_unix_address(sd_bus *b, const char **p, char **guid) {
506 _cleanup_free_ char *path = NULL, *abstract = NULL;
515 while (**p != 0 && **p != ';') {
516 r = parse_address_key(p, "guid", guid);
522 r = parse_address_key(p, "path", &path);
528 r = parse_address_key(p, "abstract", &abstract);
537 if (!path && !abstract)
540 if (path && abstract)
545 if (l > sizeof(b->sockaddr.un.sun_path))
548 b->sockaddr.un.sun_family = AF_UNIX;
549 strncpy(b->sockaddr.un.sun_path, path, sizeof(b->sockaddr.un.sun_path));
550 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l;
551 } else if (abstract) {
552 l = strlen(abstract);
553 if (l > sizeof(b->sockaddr.un.sun_path) - 1)
556 b->sockaddr.un.sun_family = AF_UNIX;
557 b->sockaddr.un.sun_path[0] = 0;
558 strncpy(b->sockaddr.un.sun_path+1, abstract, sizeof(b->sockaddr.un.sun_path)-1);
559 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
565 static int parse_tcp_address(sd_bus *b, const char **p, char **guid) {
566 _cleanup_free_ char *host = NULL, *port = NULL, *family = NULL;
568 struct addrinfo *result, hints = {
569 .ai_socktype = SOCK_STREAM,
570 .ai_flags = AI_ADDRCONFIG,
578 while (**p != 0 && **p != ';') {
579 r = parse_address_key(p, "guid", guid);
585 r = parse_address_key(p, "host", &host);
591 r = parse_address_key(p, "port", &port);
597 r = parse_address_key(p, "family", &family);
610 if (streq(family, "ipv4"))
611 hints.ai_family = AF_INET;
612 else if (streq(family, "ipv6"))
613 hints.ai_family = AF_INET6;
618 r = getaddrinfo(host, port, &hints, &result);
622 return -EADDRNOTAVAIL;
624 memcpy(&b->sockaddr, result->ai_addr, result->ai_addrlen);
625 b->sockaddr_size = result->ai_addrlen;
627 freeaddrinfo(result);
632 static int parse_exec_address(sd_bus *b, const char **p, char **guid) {
634 unsigned n_argv = 0, j;
636 size_t allocated = 0;
644 while (**p != 0 && **p != ';') {
645 r = parse_address_key(p, "guid", guid);
651 r = parse_address_key(p, "path", &path);
657 if (startswith(*p, "argv")) {
661 ul = strtoul(*p + 4, (char**) p, 10);
662 if (errno > 0 || **p != '=' || ul > 256) {
670 if (!GREEDY_REALLOC0(argv, allocated, ul + 2)) {
678 r = parse_address_key(p, NULL, argv + ul);
693 /* Make sure there are no holes in the array, with the
694 * exception of argv[0] */
695 for (j = 1; j < n_argv; j++)
701 if (argv && argv[0] == NULL) {
702 argv[0] = strdup(path);
714 for (j = 0; j < n_argv; j++)
722 static int parse_kernel_address(sd_bus *b, const char **p, char **guid) {
723 _cleanup_free_ char *path = NULL;
731 while (**p != 0 && **p != ';') {
732 r = parse_address_key(p, "guid", guid);
738 r = parse_address_key(p, "path", &path);
757 static int parse_container_unix_address(sd_bus *b, const char **p, char **guid) {
758 _cleanup_free_ char *machine = NULL;
766 while (**p != 0 && **p != ';') {
767 r = parse_address_key(p, "guid", guid);
773 r = parse_address_key(p, "machine", &machine);
785 if (!filename_is_safe(machine))
789 b->machine = machine;
792 b->sockaddr.un.sun_family = AF_UNIX;
793 strncpy(b->sockaddr.un.sun_path, "/var/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
794 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + sizeof("/var/run/dbus/system_bus_socket") - 1;
799 static int parse_container_kernel_address(sd_bus *b, const char **p, char **guid) {
800 _cleanup_free_ char *machine = NULL;
808 while (**p != 0 && **p != ';') {
809 r = parse_address_key(p, "guid", guid);
815 r = parse_address_key(p, "machine", &machine);
827 if (!filename_is_safe(machine))
831 b->machine = machine;
835 b->kernel = strdup("/dev/kdbus/0-system/bus");
842 static void bus_reset_parsed_address(sd_bus *b) {
846 b->sockaddr_size = 0;
847 strv_free(b->exec_argv);
851 b->server_id = SD_ID128_NULL;
858 static int bus_parse_next_address(sd_bus *b) {
859 _cleanup_free_ char *guid = NULL;
867 if (b->address[b->address_index] == 0)
870 bus_reset_parsed_address(b);
872 a = b->address + b->address_index;
881 if (startswith(a, "unix:")) {
884 r = parse_unix_address(b, &a, &guid);
889 } else if (startswith(a, "tcp:")) {
892 r = parse_tcp_address(b, &a, &guid);
898 } else if (startswith(a, "unixexec:")) {
901 r = parse_exec_address(b, &a, &guid);
907 } else if (startswith(a, "kernel:")) {
910 r = parse_kernel_address(b, &a, &guid);
915 } else if (startswith(a, "x-container-unix:")) {
918 r = parse_container_unix_address(b, &a, &guid);
923 } else if (startswith(a, "x-container-kernel:")) {
926 r = parse_container_kernel_address(b, &a, &guid);
939 r = sd_id128_from_string(guid, &b->server_id);
944 b->address_index = a - b->address;
948 static int bus_start_address(sd_bus *b) {
954 bool skipped = false;
959 r = bus_socket_exec(b);
960 else if (b->machine && b->kernel)
961 r = bus_container_connect_kernel(b);
962 else if (b->machine && b->sockaddr.sa.sa_family != AF_UNSPEC)
963 r = bus_container_connect_socket(b);
965 r = bus_kernel_connect(b);
966 else if (b->sockaddr.sa.sa_family != AF_UNSPEC)
967 r = bus_socket_connect(b);
973 r = attach_io_events(b);
978 b->last_connect_error = -r;
981 r = bus_parse_next_address(b);
985 return b->last_connect_error ? -b->last_connect_error : -ECONNREFUSED;
989 int bus_next_address(sd_bus *b) {
992 bus_reset_parsed_address(b);
993 return bus_start_address(b);
996 static int bus_start_fd(sd_bus *b) {
1001 assert(b->input_fd >= 0);
1002 assert(b->output_fd >= 0);
1004 r = fd_nonblock(b->input_fd, true);
1008 r = fd_cloexec(b->input_fd, true);
1012 if (b->input_fd != b->output_fd) {
1013 r = fd_nonblock(b->output_fd, true);
1017 r = fd_cloexec(b->output_fd, true);
1022 if (fstat(b->input_fd, &st) < 0)
1025 if (S_ISCHR(b->input_fd))
1026 return bus_kernel_take_fd(b);
1028 return bus_socket_take_fd(b);
1031 _public_ int sd_bus_start(sd_bus *bus) {
1034 assert_return(bus, -EINVAL);
1035 assert_return(bus->state == BUS_UNSET, -EPERM);
1036 assert_return(!bus_pid_changed(bus), -ECHILD);
1038 bus->state = BUS_OPENING;
1040 if (bus->is_server && bus->bus_client)
1043 if (bus->input_fd >= 0)
1044 r = bus_start_fd(bus);
1045 else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->kernel || bus->machine)
1046 r = bus_start_address(bus);
1053 return bus_send_hello(bus);
1056 _public_ int sd_bus_open(sd_bus **ret) {
1061 assert_return(ret, -EINVAL);
1063 /* Let's connect to the starter bus if it is set, and
1064 * otherwise to the bus that is appropropriate for the scope
1065 * we are running in */
1067 e = secure_getenv("DBUS_STARTER_BUS_TYPE");
1069 if (streq(e, "system"))
1070 return sd_bus_open_system(ret);
1071 else if (streq(e, "session") || streq(e, "user"))
1072 return sd_bus_open_user(ret);
1075 e = secure_getenv("DBUS_STARTER_ADDRESS");
1077 if (cg_pid_get_owner_uid(0, NULL) >= 0)
1078 return sd_bus_open_user(ret);
1080 return sd_bus_open_system(ret);
1087 r = sd_bus_set_address(b, e);
1091 b->bus_client = true;
1093 /* We don't know whether the bus is trusted or not, so better
1094 * be safe, and authenticate everything */
1096 b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1098 r = sd_bus_start(b);
1110 _public_ int sd_bus_open_system(sd_bus **ret) {
1115 assert_return(ret, -EINVAL);
1121 e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1123 r = sd_bus_set_address(b, e);
1125 r = sd_bus_set_address(b, DEFAULT_SYSTEM_BUS_PATH);
1129 b->bus_client = true;
1130 b->is_system = true;
1132 /* Let's do per-method access control on the system bus. We
1133 * need the caller's UID and capability set for that. */
1135 b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1137 r = sd_bus_start(b);
1149 _public_ int sd_bus_open_user(sd_bus **ret) {
1154 assert_return(ret, -EINVAL);
1160 e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
1162 r = sd_bus_set_address(b, e);
1166 e = secure_getenv("XDG_RUNTIME_DIR");
1168 _cleanup_free_ char *ee = NULL;
1170 ee = bus_address_escape(e);
1177 asprintf(&b->address, KERNEL_USER_BUS_FMT ";" UNIX_USER_BUS_FMT, (unsigned long) getuid(), ee);
1179 asprintf(&b->address, UNIX_USER_BUS_FMT, ee);
1183 asprintf(&b->address, KERNEL_USER_BUS_FMT, (unsigned long) getuid());
1185 return -ECONNREFUSED;
1195 b->bus_client = true;
1198 /* We don't do any per-method access control on the user
1202 r = sd_bus_start(b);
1214 _public_ int sd_bus_open_system_remote(const char *host, sd_bus **ret) {
1215 _cleanup_free_ char *e = NULL;
1220 assert_return(host, -EINVAL);
1221 assert_return(ret, -EINVAL);
1223 e = bus_address_escape(host);
1227 p = strjoin("unixexec:path=ssh,argv1=-xT,argv2=", e, ",argv3=systemd-stdio-bridge", NULL);
1231 r = sd_bus_new(&bus);
1238 bus->bus_client = true;
1240 r = sd_bus_start(bus);
1250 _public_ int sd_bus_open_system_container(const char *machine, sd_bus **ret) {
1251 _cleanup_free_ char *e = NULL;
1256 assert_return(machine, -EINVAL);
1257 assert_return(ret, -EINVAL);
1258 assert_return(filename_is_safe(machine), -EINVAL);
1260 e = bus_address_escape(machine);
1265 p = strjoin("x-container-kernel:machine=", e, ";x-container-unix:machine=", e, NULL);
1267 p = strjoin("x-container-unix:machine=", e, NULL);
1272 r = sd_bus_new(&bus);
1279 bus->bus_client = true;
1281 r = sd_bus_start(bus);
1291 _public_ void sd_bus_close(sd_bus *bus) {
1295 if (bus->state == BUS_CLOSED)
1297 if (bus_pid_changed(bus))
1300 bus->state = BUS_CLOSED;
1302 sd_bus_detach_event(bus);
1304 /* Drop all queued messages so that they drop references to
1305 * the bus object and the bus may be freed */
1306 bus_reset_queues(bus);
1308 if (!bus->is_kernel)
1311 /* We'll leave the fd open in case this is a kernel bus, since
1312 * there might still be memblocks around that reference this
1313 * bus, and they might need to invoke the KDBUS_CMD_FREE
1314 * ioctl on the fd when they are freed. */
1317 static void bus_enter_closing(sd_bus *bus) {
1320 if (bus->state != BUS_OPENING &&
1321 bus->state != BUS_AUTHENTICATING &&
1322 bus->state != BUS_HELLO &&
1323 bus->state != BUS_RUNNING)
1326 bus->state = BUS_CLOSING;
1329 _public_ sd_bus *sd_bus_ref(sd_bus *bus) {
1330 assert_return(bus, NULL);
1332 assert_se(REFCNT_INC(bus->n_ref) >= 2);
1337 _public_ sd_bus *sd_bus_unref(sd_bus *bus) {
1343 if (REFCNT_GET(bus->n_ref) == bus->rqueue_size + bus->wqueue_size + 1) {
1346 for (i = 0; i < bus->rqueue_size; i++)
1347 if (bus->rqueue[i]->n_ref > 1) {
1353 for (i = 0; i < bus->wqueue_size; i++)
1354 if (bus->wqueue[i]->n_ref > 1) {
1360 /* We are the only holders on the messages, and the
1361 * messages are the only holders on us, so let's drop
1362 * the messages and thus implicitly also kill our own
1363 * last references */
1365 bus_reset_queues(bus);
1368 i = REFCNT_DEC(bus->n_ref);
1376 _public_ int sd_bus_is_open(sd_bus *bus) {
1378 assert_return(bus, -EINVAL);
1379 assert_return(!bus_pid_changed(bus), -ECHILD);
1381 return BUS_IS_OPEN(bus->state);
1384 _public_ int sd_bus_can_send(sd_bus *bus, char type) {
1387 assert_return(bus, -EINVAL);
1388 assert_return(bus->state != BUS_UNSET, -ENOTCONN);
1389 assert_return(!bus_pid_changed(bus), -ECHILD);
1391 if (type == SD_BUS_TYPE_UNIX_FD) {
1392 if (!(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD))
1395 r = bus_ensure_running(bus);
1399 return bus->can_fds;
1402 return bus_type_is_valid(type);
1405 _public_ int sd_bus_get_server_id(sd_bus *bus, sd_id128_t *server_id) {
1408 assert_return(bus, -EINVAL);
1409 assert_return(server_id, -EINVAL);
1410 assert_return(!bus_pid_changed(bus), -ECHILD);
1412 r = bus_ensure_running(bus);
1416 *server_id = bus->server_id;
1420 static int bus_seal_message(sd_bus *b, sd_bus_message *m, usec_t timeout) {
1425 /* If we copy the same message to multiple
1426 * destinations, avoid using the same cookie
1428 b->cookie = MAX(b->cookie, BUS_MESSAGE_COOKIE(m));
1433 timeout = BUS_DEFAULT_TIMEOUT;
1435 return bus_message_seal(m, ++b->cookie, timeout);
1438 static int bus_remarshal_message(sd_bus *b, sd_bus_message **m) {
1441 /* Do packet version and endianess already match? */
1442 if ((b->message_version == 0 || b->message_version == (*m)->header->version) &&
1443 (b->message_endian == 0 || b->message_endian == (*m)->header->endian))
1446 /* No? Then remarshal! */
1447 return bus_message_remarshal(b, m);
1450 int bus_seal_synthetic_message(sd_bus *b, sd_bus_message *m) {
1454 /* The bus specification says the serial number cannot be 0,
1455 * hence let's fill something in for synthetic messages. Since
1456 * synthetic messages might have a fake sender and we don't
1457 * want to interfere with the real sender's serial numbers we
1458 * pick a fixed, artifical one. We use (uint32_t) -1 rather
1459 * than (uint64_t) -1 since dbus1 only had 32bit identifiers,
1460 * even though kdbus can do 64bit. */
1462 return bus_message_seal(m, 0xFFFFFFFFULL, 0);
1465 static int bus_write_message(sd_bus *bus, sd_bus_message *m, bool hint_sync_call, size_t *idx) {
1472 r = bus_kernel_write_message(bus, m, hint_sync_call);
1474 r = bus_socket_write_message(bus, m, idx);
1479 if (bus->is_kernel || *idx >= BUS_MESSAGE_SIZE(m))
1480 log_debug("Sent message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%lu reply_cookie=%lu error=%s",
1481 bus_message_type_to_string(m->header->type),
1482 strna(sd_bus_message_get_sender(m)),
1483 strna(sd_bus_message_get_destination(m)),
1484 strna(sd_bus_message_get_path(m)),
1485 strna(sd_bus_message_get_interface(m)),
1486 strna(sd_bus_message_get_member(m)),
1487 (unsigned long) BUS_MESSAGE_COOKIE(m),
1488 (unsigned long) m->reply_cookie,
1489 strna(m->error.message));
1494 static int dispatch_wqueue(sd_bus *bus) {
1498 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1500 while (bus->wqueue_size > 0) {
1502 r = bus_write_message(bus, bus->wqueue[0], false, &bus->windex);
1506 /* Didn't do anything this time */
1508 else if (bus->is_kernel || bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
1509 /* Fully written. Let's drop the entry from
1512 * This isn't particularly optimized, but
1513 * well, this is supposed to be our worst-case
1514 * buffer only, and the socket buffer is
1515 * supposed to be our primary buffer, and if
1516 * it got full, then all bets are off
1519 bus->wqueue_size --;
1520 sd_bus_message_unref(bus->wqueue[0]);
1521 memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
1531 static int bus_read_message(sd_bus *bus, bool hint_priority, int64_t priority) {
1535 return bus_kernel_read_message(bus, hint_priority, priority);
1537 return bus_socket_read_message(bus);
1540 int bus_rqueue_make_room(sd_bus *bus) {
1543 if (bus->rqueue_size >= BUS_RQUEUE_MAX)
1546 if (!GREEDY_REALLOC(bus->rqueue, bus->rqueue_allocated, bus->rqueue_size + 1))
1552 static int dispatch_rqueue(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **m) {
1557 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1559 /* Note that the priority logic is only available on kdbus,
1560 * where the rqueue is unused. We check the rqueue here
1561 * anyway, because it's simple... */
1564 if (bus->rqueue_size > 0) {
1565 /* Dispatch a queued message */
1567 *m = bus->rqueue[0];
1568 bus->rqueue_size --;
1569 memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
1573 /* Try to read a new message */
1574 r = bus_read_message(bus, hint_priority, priority);
1584 static int bus_send_internal(sd_bus *bus, sd_bus_message *_m, uint64_t *cookie, bool hint_sync_call) {
1585 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1588 assert_return(bus, -EINVAL);
1589 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1590 assert_return(m, -EINVAL);
1591 assert_return(!bus_pid_changed(bus), -ECHILD);
1594 r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
1601 /* If the cookie number isn't kept, then we know that no reply
1603 if (!cookie && !m->sealed)
1604 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1606 r = bus_seal_message(bus, m, 0);
1610 /* Remarshall if we have to. This will possibly unref the
1611 * message and place a replacement in m */
1612 r = bus_remarshal_message(bus, &m);
1616 /* If this is a reply and no reply was requested, then let's
1617 * suppress this, if we can */
1618 if (m->dont_send && !cookie)
1621 if ((bus->state == BUS_RUNNING || bus->state == BUS_HELLO) && bus->wqueue_size <= 0) {
1624 r = bus_write_message(bus, m, hint_sync_call, &idx);
1626 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
1627 bus_enter_closing(bus);
1632 } else if (!bus->is_kernel && idx < BUS_MESSAGE_SIZE(m)) {
1633 /* Wasn't fully written. So let's remember how
1634 * much was written. Note that the first entry
1635 * of the wqueue array is always allocated so
1636 * that we always can remember how much was
1638 bus->wqueue[0] = sd_bus_message_ref(m);
1639 bus->wqueue_size = 1;
1643 /* Just append it to the queue. */
1645 if (bus->wqueue_size >= BUS_WQUEUE_MAX)
1648 if (!GREEDY_REALLOC(bus->wqueue, bus->wqueue_allocated, bus->wqueue_size + 1))
1651 bus->wqueue[bus->wqueue_size ++] = sd_bus_message_ref(m);
1655 *cookie = BUS_MESSAGE_COOKIE(m);
1660 _public_ int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *cookie) {
1661 return bus_send_internal(bus, m, cookie, false);
1664 _public_ int sd_bus_send_to(sd_bus *bus, sd_bus_message *m, const char *destination, uint64_t *cookie) {
1667 assert_return(bus, -EINVAL);
1668 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1669 assert_return(m, -EINVAL);
1670 assert_return(!bus_pid_changed(bus), -ECHILD);
1672 if (!streq_ptr(m->destination, destination)) {
1677 r = sd_bus_message_set_destination(m, destination);
1682 return sd_bus_send(bus, m, cookie);
1685 static usec_t calc_elapse(uint64_t usec) {
1686 if (usec == (uint64_t) -1)
1689 return now(CLOCK_MONOTONIC) + usec;
1692 static int timeout_compare(const void *a, const void *b) {
1693 const struct reply_callback *x = a, *y = b;
1695 if (x->timeout != 0 && y->timeout == 0)
1698 if (x->timeout == 0 && y->timeout != 0)
1701 if (x->timeout < y->timeout)
1704 if (x->timeout > y->timeout)
1710 _public_ int sd_bus_call_async(
1713 sd_bus_message_handler_t callback,
1718 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1719 struct reply_callback *c;
1722 assert_return(bus, -EINVAL);
1723 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1724 assert_return(m, -EINVAL);
1725 assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1726 assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1727 assert_return(callback, -EINVAL);
1728 assert_return(!bus_pid_changed(bus), -ECHILD);
1730 r = hashmap_ensure_allocated(&bus->reply_callbacks, uint64_hash_func, uint64_compare_func);
1734 r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
1738 r = bus_seal_message(bus, m, usec);
1742 r = bus_remarshal_message(bus, &m);
1746 c = new0(struct reply_callback, 1);
1750 c->callback = callback;
1751 c->userdata = userdata;
1752 c->cookie = BUS_MESSAGE_COOKIE(m);
1753 c->timeout = calc_elapse(m->timeout);
1755 r = hashmap_put(bus->reply_callbacks, &c->cookie, c);
1761 if (c->timeout != 0) {
1762 r = prioq_put(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1765 sd_bus_call_async_cancel(bus, c->cookie);
1770 r = sd_bus_send(bus, m, cookie);
1772 sd_bus_call_async_cancel(bus, c->cookie);
1779 _public_ int sd_bus_call_async_cancel(sd_bus *bus, uint64_t cookie) {
1780 struct reply_callback *c;
1782 assert_return(bus, -EINVAL);
1783 assert_return(cookie != 0, -EINVAL);
1784 assert_return(!bus_pid_changed(bus), -ECHILD);
1786 c = hashmap_remove(bus->reply_callbacks, &cookie);
1790 if (c->timeout != 0)
1791 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1797 int bus_ensure_running(sd_bus *bus) {
1802 if (bus->state == BUS_UNSET || bus->state == BUS_CLOSED || bus->state == BUS_CLOSING)
1804 if (bus->state == BUS_RUNNING)
1808 r = sd_bus_process(bus, NULL);
1811 if (bus->state == BUS_RUNNING)
1816 r = sd_bus_wait(bus, (uint64_t) -1);
1822 _public_ int sd_bus_call(
1826 sd_bus_error *error,
1827 sd_bus_message **reply) {
1829 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1835 assert_return(bus, -EINVAL);
1836 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1837 assert_return(m, -EINVAL);
1838 assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1839 assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1840 assert_return(!bus_error_is_dirty(error), -EINVAL);
1841 assert_return(!bus_pid_changed(bus), -ECHILD);
1843 r = bus_ensure_running(bus);
1847 i = bus->rqueue_size;
1849 r = bus_seal_message(bus, m, usec);
1853 r = bus_remarshal_message(bus, &m);
1857 r = bus_send_internal(bus, m, &cookie, true);
1861 timeout = calc_elapse(m->timeout);
1866 while (i < bus->rqueue_size) {
1867 sd_bus_message *incoming = NULL;
1869 incoming = bus->rqueue[i];
1871 if (incoming->reply_cookie == cookie) {
1872 /* Found a match! */
1874 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1877 if (incoming->header->type == SD_BUS_MESSAGE_METHOD_RETURN) {
1882 sd_bus_message_unref(incoming);
1885 } else if (incoming->header->type == SD_BUS_MESSAGE_METHOD_ERROR)
1886 r = sd_bus_error_copy(error, &incoming->error);
1890 sd_bus_message_unref(incoming);
1893 } else if (BUS_MESSAGE_COOKIE(incoming) == cookie &&
1896 streq(bus->unique_name, incoming->sender)) {
1898 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1901 /* Our own message? Somebody is trying
1902 * to send its own client a message,
1903 * let's not dead-lock, let's fail
1906 sd_bus_message_unref(incoming);
1910 /* Try to read more, right-away */
1914 r = bus_read_message(bus, false, 0);
1916 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
1917 bus_enter_closing(bus);
1929 n = now(CLOCK_MONOTONIC);
1935 left = (uint64_t) -1;
1937 r = bus_poll(bus, true, left);
1943 r = dispatch_wqueue(bus);
1945 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
1946 bus_enter_closing(bus);
1955 _public_ int sd_bus_get_fd(sd_bus *bus) {
1957 assert_return(bus, -EINVAL);
1958 assert_return(bus->input_fd == bus->output_fd, -EPERM);
1959 assert_return(!bus_pid_changed(bus), -ECHILD);
1961 return bus->input_fd;
1964 _public_ int sd_bus_get_events(sd_bus *bus) {
1967 assert_return(bus, -EINVAL);
1968 assert_return(BUS_IS_OPEN(bus->state) || bus->state == BUS_CLOSING, -ENOTCONN);
1969 assert_return(!bus_pid_changed(bus), -ECHILD);
1971 if (bus->state == BUS_OPENING)
1973 else if (bus->state == BUS_AUTHENTICATING) {
1975 if (bus_socket_auth_needs_write(bus))
1980 } else if (bus->state == BUS_RUNNING || bus->state == BUS_HELLO) {
1981 if (bus->rqueue_size <= 0)
1983 if (bus->wqueue_size > 0)
1990 _public_ int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
1991 struct reply_callback *c;
1993 assert_return(bus, -EINVAL);
1994 assert_return(timeout_usec, -EINVAL);
1995 assert_return(BUS_IS_OPEN(bus->state) || bus->state == BUS_CLOSING, -ENOTCONN);
1996 assert_return(!bus_pid_changed(bus), -ECHILD);
1998 if (bus->state == BUS_CLOSING) {
2003 if (bus->state == BUS_AUTHENTICATING) {
2004 *timeout_usec = bus->auth_timeout;
2008 if (bus->state != BUS_RUNNING && bus->state != BUS_HELLO) {
2009 *timeout_usec = (uint64_t) -1;
2013 if (bus->rqueue_size > 0) {
2018 c = prioq_peek(bus->reply_callbacks_prioq);
2020 *timeout_usec = (uint64_t) -1;
2024 *timeout_usec = c->timeout;
2028 static int process_timeout(sd_bus *bus) {
2029 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2030 _cleanup_bus_message_unref_ sd_bus_message* m = NULL;
2031 struct reply_callback *c;
2037 c = prioq_peek(bus->reply_callbacks_prioq);
2041 n = now(CLOCK_MONOTONIC);
2045 r = bus_message_new_synthetic_error(
2048 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
2053 m->sender = "org.freedesktop.DBus";
2055 r = bus_seal_synthetic_message(bus, m);
2059 assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
2060 hashmap_remove(bus->reply_callbacks, &c->cookie);
2063 bus->iteration_counter ++;
2065 r = c->callback(bus, m, c->userdata, &error_buffer);
2066 r = bus_maybe_reply_error(m, r, &error_buffer);
2069 bus->current = NULL;
2074 static int process_hello(sd_bus *bus, sd_bus_message *m) {
2078 if (bus->state != BUS_HELLO)
2081 /* Let's make sure the first message on the bus is the HELLO
2082 * reply. But note that we don't actually parse the message
2083 * here (we leave that to the usual handling), we just verify
2084 * we don't let any earlier msg through. */
2086 if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2087 m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2090 if (m->reply_cookie != bus->hello_cookie)
2096 static int process_reply(sd_bus *bus, sd_bus_message *m) {
2097 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2098 struct reply_callback *c;
2104 if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2105 m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2108 c = hashmap_remove(bus->reply_callbacks, &m->reply_cookie);
2112 if (c->timeout != 0)
2113 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2115 r = sd_bus_message_rewind(m, true);
2119 r = c->callback(bus, m, c->userdata, &error_buffer);
2120 r = bus_maybe_reply_error(m, r, &error_buffer);
2126 static int process_filter(sd_bus *bus, sd_bus_message *m) {
2127 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2128 struct filter_callback *l;
2135 bus->filter_callbacks_modified = false;
2137 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
2139 if (bus->filter_callbacks_modified)
2142 /* Don't run this more than once per iteration */
2143 if (l->last_iteration == bus->iteration_counter)
2146 l->last_iteration = bus->iteration_counter;
2148 r = sd_bus_message_rewind(m, true);
2152 r = l->callback(bus, m, l->userdata, &error_buffer);
2153 r = bus_maybe_reply_error(m, r, &error_buffer);
2159 } while (bus->filter_callbacks_modified);
2164 static int process_match(sd_bus *bus, sd_bus_message *m) {
2171 bus->match_callbacks_modified = false;
2173 r = bus_match_run(bus, &bus->match_callbacks, m);
2177 } while (bus->match_callbacks_modified);
2182 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
2183 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2189 if (bus->manual_peer_interface)
2192 if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2195 if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2198 if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2201 if (streq_ptr(m->member, "Ping"))
2202 r = sd_bus_message_new_method_return(m, &reply);
2203 else if (streq_ptr(m->member, "GetMachineId")) {
2207 r = sd_id128_get_machine(&id);
2211 r = sd_bus_message_new_method_return(m, &reply);
2215 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2217 r = sd_bus_message_new_method_errorf(
2219 SD_BUS_ERROR_UNKNOWN_METHOD,
2220 "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2226 r = sd_bus_send(bus, reply, NULL);
2233 static int process_message(sd_bus *bus, sd_bus_message *m) {
2240 bus->iteration_counter++;
2242 log_debug("Got message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%lu reply_cookie=%lu error=%s",
2243 bus_message_type_to_string(m->header->type),
2244 strna(sd_bus_message_get_sender(m)),
2245 strna(sd_bus_message_get_destination(m)),
2246 strna(sd_bus_message_get_path(m)),
2247 strna(sd_bus_message_get_interface(m)),
2248 strna(sd_bus_message_get_member(m)),
2249 (unsigned long) BUS_MESSAGE_COOKIE(m),
2250 (unsigned long) m->reply_cookie,
2251 strna(m->error.message));
2253 r = process_hello(bus, m);
2257 r = process_reply(bus, m);
2261 r = process_filter(bus, m);
2265 r = process_match(bus, m);
2269 r = process_builtin(bus, m);
2273 r = bus_process_object(bus, m);
2276 bus->current = NULL;
2280 static int process_running(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2281 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2285 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
2287 r = process_timeout(bus);
2291 r = dispatch_wqueue(bus);
2295 r = dispatch_rqueue(bus, hint_priority, priority, &m);
2301 r = process_message(bus, m);
2306 r = sd_bus_message_rewind(m, true);
2315 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2317 log_debug("Unprocessed message call sender=%s object=%s interface=%s member=%s",
2318 strna(sd_bus_message_get_sender(m)),
2319 strna(sd_bus_message_get_path(m)),
2320 strna(sd_bus_message_get_interface(m)),
2321 strna(sd_bus_message_get_member(m)));
2323 r = sd_bus_reply_method_errorf(
2325 SD_BUS_ERROR_UNKNOWN_OBJECT,
2326 "Unknown object '%s'.", m->path);
2340 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2341 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2342 struct reply_callback *c;
2346 assert(bus->state == BUS_CLOSING);
2348 c = hashmap_first(bus->reply_callbacks);
2350 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2352 /* First, fail all outstanding method calls */
2353 r = bus_message_new_synthetic_error(
2356 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2361 r = bus_seal_synthetic_message(bus, m);
2365 if (c->timeout != 0)
2366 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2368 hashmap_remove(bus->reply_callbacks, &c->cookie);
2371 bus->iteration_counter++;
2373 r = c->callback(bus, m, c->userdata, &error_buffer);
2374 r = bus_maybe_reply_error(m, r, &error_buffer);
2380 /* Then, synthesize a Disconnected message */
2381 r = sd_bus_message_new_signal(
2383 "/org/freedesktop/DBus/Local",
2384 "org.freedesktop.DBus.Local",
2390 m->sender = "org.freedesktop.DBus.Local";
2392 r = bus_seal_synthetic_message(bus, m);
2399 bus->iteration_counter++;
2401 r = process_filter(bus, m);
2405 r = process_match(bus, m);
2417 bus->current = NULL;
2421 static int bus_process_internal(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2422 BUS_DONT_DESTROY(bus);
2425 /* Returns 0 when we didn't do anything. This should cause the
2426 * caller to invoke sd_bus_wait() before returning the next
2427 * time. Returns > 0 when we did something, which possibly
2428 * means *ret is filled in with an unprocessed message. */
2430 assert_return(bus, -EINVAL);
2431 assert_return(!bus_pid_changed(bus), -ECHILD);
2433 /* We don't allow recursively invoking sd_bus_process(). */
2434 assert_return(!bus->current, -EBUSY);
2436 switch (bus->state) {
2445 r = bus_socket_process_opening(bus);
2446 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2447 bus_enter_closing(bus);
2455 case BUS_AUTHENTICATING:
2456 r = bus_socket_process_authenticating(bus);
2457 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2458 bus_enter_closing(bus);
2470 r = process_running(bus, hint_priority, priority, ret);
2471 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2472 bus_enter_closing(bus);
2482 return process_closing(bus, ret);
2485 assert_not_reached("Unknown state");
2488 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2489 return bus_process_internal(bus, false, 0, ret);
2492 _public_ int sd_bus_process_priority(sd_bus *bus, int64_t priority, sd_bus_message **ret) {
2493 return bus_process_internal(bus, true, priority, ret);
2496 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2497 struct pollfd p[2] = {};
2500 usec_t m = (usec_t) -1;
2504 if (bus->state == BUS_CLOSING)
2507 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2509 e = sd_bus_get_events(bus);
2514 /* The caller really needs some more data, he doesn't
2515 * care about what's already read, or any timeouts
2520 /* The caller wants to process if there's something to
2521 * process, but doesn't care otherwise */
2523 r = sd_bus_get_timeout(bus, &until);
2528 nw = now(CLOCK_MONOTONIC);
2529 m = until > nw ? until - nw : 0;
2533 if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
2536 p[0].fd = bus->input_fd;
2537 if (bus->output_fd == bus->input_fd) {
2541 p[0].events = e & POLLIN;
2542 p[1].fd = bus->output_fd;
2543 p[1].events = e & POLLOUT;
2547 r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
2551 return r > 0 ? 1 : 0;
2554 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
2556 assert_return(bus, -EINVAL);
2557 assert_return(!bus_pid_changed(bus), -ECHILD);
2559 if (bus->state == BUS_CLOSING)
2562 assert_return(BUS_IS_OPEN(bus->state) , -ENOTCONN);
2564 if (bus->rqueue_size > 0)
2567 return bus_poll(bus, false, timeout_usec);
2570 _public_ int sd_bus_flush(sd_bus *bus) {
2573 assert_return(bus, -EINVAL);
2574 assert_return(!bus_pid_changed(bus), -ECHILD);
2576 if (bus->state == BUS_CLOSING)
2579 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2581 r = bus_ensure_running(bus);
2585 if (bus->wqueue_size <= 0)
2589 r = dispatch_wqueue(bus);
2591 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2592 bus_enter_closing(bus);
2599 if (bus->wqueue_size <= 0)
2602 r = bus_poll(bus, false, (uint64_t) -1);
2608 _public_ int sd_bus_add_filter(sd_bus *bus,
2609 sd_bus_message_handler_t callback,
2612 struct filter_callback *f;
2614 assert_return(bus, -EINVAL);
2615 assert_return(callback, -EINVAL);
2616 assert_return(!bus_pid_changed(bus), -ECHILD);
2618 f = new0(struct filter_callback, 1);
2621 f->callback = callback;
2622 f->userdata = userdata;
2624 bus->filter_callbacks_modified = true;
2625 LIST_PREPEND(callbacks, bus->filter_callbacks, f);
2629 _public_ int sd_bus_remove_filter(sd_bus *bus,
2630 sd_bus_message_handler_t callback,
2633 struct filter_callback *f;
2635 assert_return(bus, -EINVAL);
2636 assert_return(callback, -EINVAL);
2637 assert_return(!bus_pid_changed(bus), -ECHILD);
2639 LIST_FOREACH(callbacks, f, bus->filter_callbacks) {
2640 if (f->callback == callback && f->userdata == userdata) {
2641 bus->filter_callbacks_modified = true;
2642 LIST_REMOVE(callbacks, bus->filter_callbacks, f);
2651 _public_ int sd_bus_add_match(sd_bus *bus,
2653 sd_bus_message_handler_t callback,
2656 struct bus_match_component *components = NULL;
2657 unsigned n_components = 0;
2658 uint64_t cookie = 0;
2661 assert_return(bus, -EINVAL);
2662 assert_return(match, -EINVAL);
2663 assert_return(!bus_pid_changed(bus), -ECHILD);
2665 r = bus_match_parse(match, &components, &n_components);
2669 if (bus->bus_client) {
2670 cookie = ++bus->match_cookie;
2672 r = bus_add_match_internal(bus, match, components, n_components, cookie);
2677 bus->match_callbacks_modified = true;
2678 r = bus_match_add(&bus->match_callbacks, components, n_components, callback, userdata, cookie, NULL);
2680 if (bus->bus_client)
2681 bus_remove_match_internal(bus, match, cookie);
2685 bus_match_parse_free(components, n_components);
2689 _public_ int sd_bus_remove_match(sd_bus *bus,
2691 sd_bus_message_handler_t callback,
2694 struct bus_match_component *components = NULL;
2695 unsigned n_components = 0;
2697 uint64_t cookie = 0;
2699 assert_return(bus, -EINVAL);
2700 assert_return(match, -EINVAL);
2701 assert_return(!bus_pid_changed(bus), -ECHILD);
2703 r = bus_match_parse(match, &components, &n_components);
2707 bus->match_callbacks_modified = true;
2708 r = bus_match_remove(&bus->match_callbacks, components, n_components, callback, userdata, &cookie);
2710 if (bus->bus_client)
2711 q = bus_remove_match_internal(bus, match, cookie);
2713 bus_match_parse_free(components, n_components);
2715 return r < 0 ? r : q;
2718 bool bus_pid_changed(sd_bus *bus) {
2721 /* We don't support people creating a bus connection and
2722 * keeping it around over a fork(). Let's complain. */
2724 return bus->original_pid != getpid();
2727 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2728 sd_bus *bus = userdata;
2733 r = sd_bus_process(bus, NULL);
2740 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
2741 sd_bus *bus = userdata;
2746 r = sd_bus_process(bus, NULL);
2753 static int prepare_callback(sd_event_source *s, void *userdata) {
2754 sd_bus *bus = userdata;
2761 e = sd_bus_get_events(bus);
2765 if (bus->output_fd != bus->input_fd) {
2767 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
2771 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
2775 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
2780 r = sd_bus_get_timeout(bus, &until);
2786 j = sd_event_source_set_time(bus->time_event_source, until);
2791 r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
2798 static int quit_callback(sd_event_source *event, void *userdata) {
2799 sd_bus *bus = userdata;
2808 static int attach_io_events(sd_bus *bus) {
2813 if (bus->input_fd < 0)
2819 if (!bus->input_io_event_source) {
2820 r = sd_event_add_io(bus->event, bus->input_fd, 0, io_callback, bus, &bus->input_io_event_source);
2824 r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
2828 r = sd_event_source_set_priority(bus->input_io_event_source, bus->event_priority);
2830 r = sd_event_source_set_io_fd(bus->input_io_event_source, bus->input_fd);
2835 if (bus->output_fd != bus->input_fd) {
2836 assert(bus->output_fd >= 0);
2838 if (!bus->output_io_event_source) {
2839 r = sd_event_add_io(bus->event, bus->output_fd, 0, io_callback, bus, &bus->output_io_event_source);
2843 r = sd_event_source_set_priority(bus->output_io_event_source, bus->event_priority);
2845 r = sd_event_source_set_io_fd(bus->output_io_event_source, bus->output_fd);
2854 static void detach_io_events(sd_bus *bus) {
2857 if (bus->input_io_event_source) {
2858 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
2859 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
2862 if (bus->output_io_event_source) {
2863 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
2864 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
2868 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
2871 assert_return(bus, -EINVAL);
2872 assert_return(!bus->event, -EBUSY);
2874 assert(!bus->input_io_event_source);
2875 assert(!bus->output_io_event_source);
2876 assert(!bus->time_event_source);
2879 bus->event = sd_event_ref(event);
2881 r = sd_event_default(&bus->event);
2886 bus->event_priority = priority;
2888 r = sd_event_add_monotonic(bus->event, 0, 0, time_callback, bus, &bus->time_event_source);
2892 r = sd_event_source_set_priority(bus->time_event_source, priority);
2896 r = sd_event_add_exit(bus->event, quit_callback, bus, &bus->quit_event_source);
2900 r = attach_io_events(bus);
2907 sd_bus_detach_event(bus);
2911 _public_ int sd_bus_detach_event(sd_bus *bus) {
2912 assert_return(bus, -EINVAL);
2917 detach_io_events(bus);
2919 if (bus->time_event_source) {
2920 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
2921 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
2924 if (bus->quit_event_source) {
2925 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
2926 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
2930 bus->event = sd_event_unref(bus->event);
2935 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
2936 assert_return(bus, NULL);
2941 _public_ sd_bus_message* sd_bus_get_current(sd_bus *bus) {
2942 assert_return(bus, NULL);
2944 return bus->current;
2947 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
2952 assert(default_bus);
2955 return !!*default_bus;
2958 *ret = sd_bus_ref(*default_bus);
2966 b->default_bus_ptr = default_bus;
2974 _public_ int sd_bus_default_system(sd_bus **ret) {
2975 static thread_local sd_bus *default_system_bus = NULL;
2977 return bus_default(sd_bus_open_system, &default_system_bus, ret);
2980 _public_ int sd_bus_default_user(sd_bus **ret) {
2981 static thread_local sd_bus *default_user_bus = NULL;
2983 return bus_default(sd_bus_open_user, &default_user_bus, ret);
2986 _public_ int sd_bus_default(sd_bus **ret) {
2990 /* Let's try our best to reuse another cached connection. If
2991 * the starter bus type is set, connect via our normal
2992 * connection logic, ignoring $DBUS_STARTER_ADDRESS, so that
2993 * we can share the connection with the user/system default
2996 e = secure_getenv("DBUS_STARTER_BUS_TYPE");
2998 if (streq(e, "system"))
2999 return sd_bus_default_system(ret);
3000 else if (streq(e, "user") || streq(e, "session"))
3001 return sd_bus_default_user(ret);
3004 /* No type is specified, so we have not other option than to
3005 * use the starter address if it is set. */
3007 e = secure_getenv("DBUS_STARTER_ADDRESS");
3009 static thread_local sd_bus *default_starter_bus = NULL;
3011 return bus_default(sd_bus_open, &default_starter_bus, ret);
3014 /* Finally, if nothing is set use the cached connection for
3015 * the right scope */
3017 if (cg_pid_get_owner_uid(0, NULL) >= 0)
3018 return sd_bus_default_user(ret);
3020 return sd_bus_default_system(ret);
3023 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
3024 assert_return(b, -EINVAL);
3025 assert_return(tid, -EINVAL);
3026 assert_return(!bus_pid_changed(b), -ECHILD);
3034 return sd_event_get_tid(b->event, tid);
3039 _public_ char *sd_bus_label_escape(const char *s) {
3043 assert_return(s, NULL);
3045 /* Escapes all chars that D-Bus' object path cannot deal
3046 * with. Can be reversed with bus_path_unescape(). We special
3047 * case the empty string. */
3052 r = new(char, strlen(s)*3 + 1);
3056 for (f = s, t = r; *f; f++) {
3058 /* Escape everything that is not a-zA-Z0-9. We also
3059 * escape 0-9 if it's the first character */
3061 if (!(*f >= 'A' && *f <= 'Z') &&
3062 !(*f >= 'a' && *f <= 'z') &&
3063 !(f > s && *f >= '0' && *f <= '9')) {
3065 *(t++) = hexchar(*f >> 4);
3066 *(t++) = hexchar(*f);
3076 _public_ char *sd_bus_label_unescape(const char *f) {
3079 assert_return(f, NULL);
3081 /* Special case for the empty string */
3085 r = new(char, strlen(f) + 1);
3089 for (t = r; *f; f++) {
3094 if ((a = unhexchar(f[1])) < 0 ||
3095 (b = unhexchar(f[2])) < 0) {
3096 /* Invalid escape code, let's take it literal then */
3099 *(t++) = (char) ((a << 4) | b);
3111 _public_ int sd_bus_get_peer_creds(sd_bus *bus, uint64_t mask, sd_bus_creds **ret) {
3116 assert_return(bus, -EINVAL);
3117 assert_return(mask <= _SD_BUS_CREDS_ALL, -ENOTSUP);
3118 assert_return(ret, -EINVAL);
3119 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
3120 assert_return(!bus_pid_changed(bus), -ECHILD);
3121 assert_return(!bus->is_kernel, -ENOTSUP);
3123 if (!bus->ucred_valid && !isempty(bus->label))
3126 c = bus_creds_new();
3130 if (bus->ucred_valid) {
3131 pid = c->pid = bus->ucred.pid;
3132 c->uid = bus->ucred.uid;
3133 c->gid = bus->ucred.gid;
3135 c->mask |= (SD_BUS_CREDS_UID | SD_BUS_CREDS_PID | SD_BUS_CREDS_GID) & mask;
3138 if (!isempty(bus->label) && (mask & SD_BUS_CREDS_SELINUX_CONTEXT)) {
3139 c->label = strdup(bus->label);
3141 sd_bus_creds_unref(c);
3145 c->mask |= SD_BUS_CREDS_SELINUX_CONTEXT;
3148 r = bus_creds_add_more(c, mask, pid, 0);
3156 _public_ int sd_bus_try_close(sd_bus *bus) {
3159 assert_return(bus, -EINVAL);
3160 assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
3161 assert_return(!bus_pid_changed(bus), -ECHILD);
3162 assert_return(bus->is_kernel, -ENOTSUP);
3164 if (bus->rqueue_size > 0)
3167 if (bus->wqueue_size > 0)
3170 r = bus_kernel_try_close(bus);
3178 _public_ int sd_bus_get_name(sd_bus *bus, const char **name) {
3179 assert_return(bus, -EINVAL);
3180 assert_return(name, -EINVAL);
3181 assert_return(!bus_pid_changed(bus), -ECHILD);
3183 *name = bus->connection_name;