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"
39 #include "bus-label.h"
42 #include "bus-internal.h"
43 #include "bus-message.h"
45 #include "bus-socket.h"
46 #include "bus-kernel.h"
47 #include "bus-control.h"
48 #include "bus-introspect.h"
49 #include "bus-signature.h"
50 #include "bus-objects.h"
52 #include "bus-container.h"
53 #include "bus-protocol.h"
54 #include "bus-track.h"
57 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec);
58 static int attach_io_events(sd_bus *b);
59 static void detach_io_events(sd_bus *b);
61 static void bus_close_fds(sd_bus *b) {
67 safe_close(b->input_fd);
69 if (b->output_fd >= 0 && b->output_fd != b->input_fd)
70 safe_close(b->output_fd);
72 b->input_fd = b->output_fd = -1;
75 static void bus_reset_queues(sd_bus *b) {
78 while (b->rqueue_size > 0)
79 sd_bus_message_unref(b->rqueue[--b->rqueue_size]);
83 b->rqueue_allocated = 0;
85 while (b->wqueue_size > 0)
86 sd_bus_message_unref(b->wqueue[--b->wqueue_size]);
90 b->wqueue_allocated = 0;
93 static void bus_free(sd_bus *b) {
97 assert(!b->track_queue);
99 b->state = BUS_CLOSED;
101 sd_bus_detach_event(b);
103 while ((s = b->slots)) {
104 /* At this point only floating slots can still be
105 * around, because the non-floating ones keep a
106 * reference to the bus, and we thus couldn't be
107 * destructing right now... We forcibly disconnect the
108 * slots here, so that they still can be referenced by
109 * apps, but are dead. */
112 bus_slot_disconnect(s);
113 sd_bus_slot_unref(s);
116 if (b->default_bus_ptr)
117 *b->default_bus_ptr = NULL;
122 munmap(b->kdbus_buffer, KDBUS_POOL_SIZE);
125 free(b->unique_name);
126 free(b->auth_buffer);
131 free(b->cgroup_root);
132 free(b->description);
135 strv_free(b->exec_argv);
137 close_many(b->fds, b->n_fds);
142 ordered_hashmap_free_free(b->reply_callbacks);
143 prioq_free(b->reply_callbacks_prioq);
145 assert(b->match_callbacks.type == BUS_MATCH_ROOT);
146 bus_match_free(&b->match_callbacks);
148 hashmap_free_free(b->vtable_methods);
149 hashmap_free_free(b->vtable_properties);
151 assert(hashmap_isempty(b->nodes));
152 hashmap_free(b->nodes);
154 bus_kernel_flush_memfd(b);
156 assert_se(pthread_mutex_destroy(&b->memfd_cache_mutex) == 0);
161 _public_ int sd_bus_new(sd_bus **ret) {
164 assert_return(ret, -EINVAL);
170 r->n_ref = REFCNT_INIT;
171 r->input_fd = r->output_fd = -1;
172 r->message_version = 1;
173 r->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
174 r->hello_flags |= KDBUS_HELLO_ACCEPT_FD;
175 r->attach_flags |= KDBUS_ATTACH_NAMES;
176 r->original_pid = getpid();
178 assert_se(pthread_mutex_init(&r->memfd_cache_mutex, NULL) == 0);
180 /* We guarantee that wqueue always has space for at least one
182 if (!GREEDY_REALLOC(r->wqueue, r->wqueue_allocated, 1)) {
191 _public_ int sd_bus_set_address(sd_bus *bus, const char *address) {
194 assert_return(bus, -EINVAL);
195 assert_return(bus->state == BUS_UNSET, -EPERM);
196 assert_return(address, -EINVAL);
197 assert_return(!bus_pid_changed(bus), -ECHILD);
209 _public_ int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd) {
210 assert_return(bus, -EINVAL);
211 assert_return(bus->state == BUS_UNSET, -EPERM);
212 assert_return(input_fd >= 0, -EINVAL);
213 assert_return(output_fd >= 0, -EINVAL);
214 assert_return(!bus_pid_changed(bus), -ECHILD);
216 bus->input_fd = input_fd;
217 bus->output_fd = output_fd;
221 _public_ int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]) {
224 assert_return(bus, -EINVAL);
225 assert_return(bus->state == BUS_UNSET, -EPERM);
226 assert_return(path, -EINVAL);
227 assert_return(!strv_isempty(argv), -EINVAL);
228 assert_return(!bus_pid_changed(bus), -ECHILD);
240 free(bus->exec_path);
241 strv_free(bus->exec_argv);
249 _public_ int sd_bus_set_bus_client(sd_bus *bus, int b) {
250 assert_return(bus, -EINVAL);
251 assert_return(bus->state == BUS_UNSET, -EPERM);
252 assert_return(!bus_pid_changed(bus), -ECHILD);
254 bus->bus_client = !!b;
258 _public_ int sd_bus_set_monitor(sd_bus *bus, int b) {
259 assert_return(bus, -EINVAL);
260 assert_return(bus->state == BUS_UNSET, -EPERM);
261 assert_return(!bus_pid_changed(bus), -ECHILD);
263 SET_FLAG(bus->hello_flags, KDBUS_HELLO_MONITOR, b);
267 _public_ int sd_bus_negotiate_fds(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 SET_FLAG(bus->hello_flags, KDBUS_HELLO_ACCEPT_FD, b);
276 _public_ int sd_bus_negotiate_timestamp(sd_bus *bus, int b) {
278 assert_return(bus, -EINVAL);
279 assert_return(!IN_SET(bus->state, BUS_CLOSING, BUS_CLOSED), -EPERM);
280 assert_return(!bus_pid_changed(bus), -ECHILD);
282 new_flags = bus->attach_flags;
283 SET_FLAG(new_flags, KDBUS_ATTACH_TIMESTAMP, b);
285 if (bus->attach_flags == new_flags)
288 bus->attach_flags = new_flags;
289 if (bus->state != BUS_UNSET && bus->is_kernel)
290 bus_kernel_realize_attach_flags(bus);
295 _public_ int sd_bus_negotiate_creds(sd_bus *bus, int b, uint64_t mask) {
298 assert_return(bus, -EINVAL);
299 assert_return(mask <= _SD_BUS_CREDS_ALL, -EINVAL);
300 assert_return(!IN_SET(bus->state, BUS_CLOSING, BUS_CLOSED), -EPERM);
301 assert_return(!bus_pid_changed(bus), -ECHILD);
304 bus->creds_mask |= mask;
306 bus->creds_mask &= ~mask;
308 /* The well knowns we need unconditionally, so that matches can work */
309 bus->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
311 /* Make sure we don't lose the timestamp flag */
312 new_flags = (bus->attach_flags & KDBUS_ATTACH_TIMESTAMP) | attach_flags_to_kdbus(bus->creds_mask);
313 if (bus->attach_flags == new_flags)
316 bus->attach_flags = new_flags;
317 if (bus->state != BUS_UNSET && bus->is_kernel)
318 bus_kernel_realize_attach_flags(bus);
323 _public_ int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id) {
324 assert_return(bus, -EINVAL);
325 assert_return(b || sd_id128_equal(server_id, SD_ID128_NULL), -EINVAL);
326 assert_return(bus->state == BUS_UNSET, -EPERM);
327 assert_return(!bus_pid_changed(bus), -ECHILD);
329 bus->is_server = !!b;
330 bus->server_id = server_id;
334 _public_ int sd_bus_set_anonymous(sd_bus *bus, int b) {
335 assert_return(bus, -EINVAL);
336 assert_return(bus->state == BUS_UNSET, -EPERM);
337 assert_return(!bus_pid_changed(bus), -ECHILD);
339 bus->anonymous_auth = !!b;
343 _public_ int sd_bus_set_trusted(sd_bus *bus, int b) {
344 assert_return(bus, -EINVAL);
345 assert_return(bus->state == BUS_UNSET, -EPERM);
346 assert_return(!bus_pid_changed(bus), -ECHILD);
352 _public_ int sd_bus_set_description(sd_bus *bus, const char *description) {
353 assert_return(bus, -EINVAL);
354 assert_return(bus->state == BUS_UNSET, -EPERM);
355 assert_return(!bus_pid_changed(bus), -ECHILD);
357 return free_and_strdup(&bus->description, description);
360 _public_ int sd_bus_set_allow_interactive_authorization(sd_bus *bus, int b) {
361 assert_return(bus, -EINVAL);
362 assert_return(!bus_pid_changed(bus), -ECHILD);
364 bus->allow_interactive_authorization = !!b;
368 _public_ int sd_bus_get_allow_interactive_authorization(sd_bus *bus) {
369 assert_return(bus, -EINVAL);
370 assert_return(!bus_pid_changed(bus), -ECHILD);
372 return bus->allow_interactive_authorization;
375 static int hello_callback(sd_bus *bus, sd_bus_message *reply, void *userdata, sd_bus_error *error) {
380 assert(bus->state == BUS_HELLO || bus->state == BUS_CLOSING);
383 r = sd_bus_message_get_errno(reply);
387 r = sd_bus_message_read(reply, "s", &s);
391 if (!service_name_is_valid(s) || s[0] != ':')
394 bus->unique_name = strdup(s);
395 if (!bus->unique_name)
398 if (bus->state == BUS_HELLO)
399 bus->state = BUS_RUNNING;
404 static int bus_send_hello(sd_bus *bus) {
405 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
410 if (!bus->bus_client || bus->is_kernel)
413 r = sd_bus_message_new_method_call(
416 "org.freedesktop.DBus",
417 "/org/freedesktop/DBus",
418 "org.freedesktop.DBus",
423 return sd_bus_call_async(bus, NULL, m, hello_callback, NULL, 0);
426 int bus_start_running(sd_bus *bus) {
429 if (bus->bus_client && !bus->is_kernel) {
430 bus->state = BUS_HELLO;
434 bus->state = BUS_RUNNING;
438 static int parse_address_key(const char **p, const char *key, char **value) {
439 size_t l, n = 0, allocated = 0;
449 if (strncmp(*p, key, l) != 0)
462 while (*a != ';' && *a != ',' && *a != 0) {
480 c = (char) ((x << 4) | y);
487 if (!GREEDY_REALLOC(r, allocated, n + 2))
511 static void skip_address_key(const char **p) {
515 *p += strcspn(*p, ",");
521 static int parse_unix_address(sd_bus *b, const char **p, char **guid) {
522 _cleanup_free_ char *path = NULL, *abstract = NULL;
531 while (**p != 0 && **p != ';') {
532 r = parse_address_key(p, "guid", guid);
538 r = parse_address_key(p, "path", &path);
544 r = parse_address_key(p, "abstract", &abstract);
553 if (!path && !abstract)
556 if (path && abstract)
561 if (l > sizeof(b->sockaddr.un.sun_path))
564 b->sockaddr.un.sun_family = AF_UNIX;
565 strncpy(b->sockaddr.un.sun_path, path, sizeof(b->sockaddr.un.sun_path));
566 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l;
567 } else if (abstract) {
568 l = strlen(abstract);
569 if (l > sizeof(b->sockaddr.un.sun_path) - 1)
572 b->sockaddr.un.sun_family = AF_UNIX;
573 b->sockaddr.un.sun_path[0] = 0;
574 strncpy(b->sockaddr.un.sun_path+1, abstract, sizeof(b->sockaddr.un.sun_path)-1);
575 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
581 static int parse_tcp_address(sd_bus *b, const char **p, char **guid) {
582 _cleanup_free_ char *host = NULL, *port = NULL, *family = NULL;
584 struct addrinfo *result, hints = {
585 .ai_socktype = SOCK_STREAM,
586 .ai_flags = AI_ADDRCONFIG,
594 while (**p != 0 && **p != ';') {
595 r = parse_address_key(p, "guid", guid);
601 r = parse_address_key(p, "host", &host);
607 r = parse_address_key(p, "port", &port);
613 r = parse_address_key(p, "family", &family);
626 if (streq(family, "ipv4"))
627 hints.ai_family = AF_INET;
628 else if (streq(family, "ipv6"))
629 hints.ai_family = AF_INET6;
634 r = getaddrinfo(host, port, &hints, &result);
638 return -EADDRNOTAVAIL;
640 memcpy(&b->sockaddr, result->ai_addr, result->ai_addrlen);
641 b->sockaddr_size = result->ai_addrlen;
643 freeaddrinfo(result);
648 static int parse_exec_address(sd_bus *b, const char **p, char **guid) {
650 unsigned n_argv = 0, j;
652 size_t allocated = 0;
660 while (**p != 0 && **p != ';') {
661 r = parse_address_key(p, "guid", guid);
667 r = parse_address_key(p, "path", &path);
673 if (startswith(*p, "argv")) {
677 ul = strtoul(*p + 4, (char**) p, 10);
678 if (errno > 0 || **p != '=' || ul > 256) {
686 if (!GREEDY_REALLOC0(argv, allocated, ul + 2)) {
694 r = parse_address_key(p, NULL, argv + ul);
709 /* Make sure there are no holes in the array, with the
710 * exception of argv[0] */
711 for (j = 1; j < n_argv; j++)
717 if (argv && argv[0] == NULL) {
718 argv[0] = strdup(path);
730 for (j = 0; j < n_argv; j++)
738 static int parse_kernel_address(sd_bus *b, const char **p, char **guid) {
739 _cleanup_free_ char *path = NULL;
747 while (**p != 0 && **p != ';') {
748 r = parse_address_key(p, "guid", guid);
754 r = parse_address_key(p, "path", &path);
773 static int parse_container_unix_address(sd_bus *b, const char **p, char **guid) {
774 _cleanup_free_ char *machine = NULL, *pid = NULL;
782 while (**p != 0 && **p != ';') {
783 r = parse_address_key(p, "guid", guid);
789 r = parse_address_key(p, "machine", &machine);
795 r = parse_address_key(p, "pid", &pid);
804 if (!machine == !pid)
808 if (!machine_name_is_valid(machine))
812 b->machine = machine;
820 r = parse_pid(pid, &b->nspid);
826 b->sockaddr.un.sun_family = AF_UNIX;
827 strncpy(b->sockaddr.un.sun_path, "/var/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
828 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen("/var/run/dbus/system_bus_socket");
833 static int parse_container_kernel_address(sd_bus *b, const char **p, char **guid) {
834 _cleanup_free_ char *machine = NULL, *pid = NULL;
842 while (**p != 0 && **p != ';') {
843 r = parse_address_key(p, "guid", guid);
849 r = parse_address_key(p, "machine", &machine);
855 r = parse_address_key(p, "pid", &pid);
864 if (!machine == !pid)
868 if (!machine_name_is_valid(machine))
872 b->machine = machine;
880 r = parse_pid(pid, &b->nspid);
887 b->kernel = strdup("/sys/fs/kdbus/0-system/bus");
894 static void bus_reset_parsed_address(sd_bus *b) {
898 b->sockaddr_size = 0;
899 strv_free(b->exec_argv);
903 b->server_id = SD_ID128_NULL;
911 static int bus_parse_next_address(sd_bus *b) {
912 _cleanup_free_ char *guid = NULL;
920 if (b->address[b->address_index] == 0)
923 bus_reset_parsed_address(b);
925 a = b->address + b->address_index;
934 if (startswith(a, "unix:")) {
937 r = parse_unix_address(b, &a, &guid);
942 } else if (startswith(a, "tcp:")) {
945 r = parse_tcp_address(b, &a, &guid);
951 } else if (startswith(a, "unixexec:")) {
954 r = parse_exec_address(b, &a, &guid);
960 } else if (startswith(a, "kernel:")) {
963 r = parse_kernel_address(b, &a, &guid);
968 } else if (startswith(a, "x-machine-unix:")) {
971 r = parse_container_unix_address(b, &a, &guid);
976 } else if (startswith(a, "x-machine-kernel:")) {
979 r = parse_container_kernel_address(b, &a, &guid);
992 r = sd_id128_from_string(guid, &b->server_id);
997 b->address_index = a - b->address;
1001 static int bus_start_address(sd_bus *b) {
1007 bool skipped = false;
1012 r = bus_socket_exec(b);
1013 else if ((b->nspid > 0 || b->machine) && b->kernel)
1014 r = bus_container_connect_kernel(b);
1015 else if ((b->nspid > 0 || b->machine) && b->sockaddr.sa.sa_family != AF_UNSPEC)
1016 r = bus_container_connect_socket(b);
1018 r = bus_kernel_connect(b);
1019 else if (b->sockaddr.sa.sa_family != AF_UNSPEC)
1020 r = bus_socket_connect(b);
1026 r = attach_io_events(b);
1031 b->last_connect_error = -r;
1034 r = bus_parse_next_address(b);
1038 return b->last_connect_error ? -b->last_connect_error : -ECONNREFUSED;
1042 int bus_next_address(sd_bus *b) {
1045 bus_reset_parsed_address(b);
1046 return bus_start_address(b);
1049 static int bus_start_fd(sd_bus *b) {
1054 assert(b->input_fd >= 0);
1055 assert(b->output_fd >= 0);
1057 r = fd_nonblock(b->input_fd, true);
1061 r = fd_cloexec(b->input_fd, true);
1065 if (b->input_fd != b->output_fd) {
1066 r = fd_nonblock(b->output_fd, true);
1070 r = fd_cloexec(b->output_fd, true);
1075 if (fstat(b->input_fd, &st) < 0)
1078 if (S_ISCHR(b->input_fd))
1079 return bus_kernel_take_fd(b);
1081 return bus_socket_take_fd(b);
1084 _public_ int sd_bus_start(sd_bus *bus) {
1087 assert_return(bus, -EINVAL);
1088 assert_return(bus->state == BUS_UNSET, -EPERM);
1089 assert_return(!bus_pid_changed(bus), -ECHILD);
1091 bus->state = BUS_OPENING;
1093 if (bus->is_server && bus->bus_client)
1096 if (bus->input_fd >= 0)
1097 r = bus_start_fd(bus);
1098 else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->kernel || bus->machine)
1099 r = bus_start_address(bus);
1108 return bus_send_hello(bus);
1111 _public_ int sd_bus_open(sd_bus **ret) {
1116 assert_return(ret, -EINVAL);
1118 /* Let's connect to the starter bus if it is set, and
1119 * otherwise to the bus that is appropropriate for the scope
1120 * we are running in */
1122 e = secure_getenv("DBUS_STARTER_BUS_TYPE");
1124 if (streq(e, "system"))
1125 return sd_bus_open_system(ret);
1126 else if (STR_IN_SET(e, "session", "user"))
1127 return sd_bus_open_user(ret);
1130 e = secure_getenv("DBUS_STARTER_ADDRESS");
1132 if (cg_pid_get_owner_uid(0, NULL) >= 0)
1133 return sd_bus_open_user(ret);
1135 return sd_bus_open_system(ret);
1142 r = sd_bus_set_address(b, e);
1146 b->bus_client = true;
1148 /* We don't know whether the bus is trusted or not, so better
1149 * be safe, and authenticate everything */
1151 b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1152 b->creds_mask |= SD_BUS_CREDS_UID | SD_BUS_CREDS_EUID | SD_BUS_CREDS_EFFECTIVE_CAPS;
1154 r = sd_bus_start(b);
1166 int bus_set_address_system(sd_bus *b) {
1170 e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1172 return sd_bus_set_address(b, e);
1174 return sd_bus_set_address(b, DEFAULT_SYSTEM_BUS_ADDRESS);
1177 _public_ int sd_bus_open_system(sd_bus **ret) {
1181 assert_return(ret, -EINVAL);
1187 r = bus_set_address_system(b);
1191 b->bus_client = true;
1192 b->is_system = true;
1194 /* Let's do per-method access control on the system bus. We
1195 * need the caller's UID and capability set for that. */
1197 b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1198 b->creds_mask |= SD_BUS_CREDS_UID | SD_BUS_CREDS_EUID | SD_BUS_CREDS_EFFECTIVE_CAPS;
1200 r = sd_bus_start(b);
1212 int bus_set_address_user(sd_bus *b) {
1217 e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
1219 return sd_bus_set_address(b, e);
1221 e = secure_getenv("XDG_RUNTIME_DIR");
1223 _cleanup_free_ char *ee = NULL;
1225 ee = bus_address_escape(e);
1230 (void) asprintf(&b->address, KERNEL_USER_BUS_ADDRESS_FMT ";" UNIX_USER_BUS_ADDRESS_FMT, getuid(), ee);
1232 (void) asprintf(&b->address, UNIX_USER_BUS_ADDRESS_FMT, ee);
1236 (void) asprintf(&b->address, KERNEL_USER_BUS_ADDRESS_FMT, getuid());
1238 return -ECONNREFUSED;
1248 _public_ int sd_bus_open_user(sd_bus **ret) {
1252 assert_return(ret, -EINVAL);
1258 r = bus_set_address_user(b);
1262 b->bus_client = true;
1265 /* We don't do any per-method access control on the user
1269 r = sd_bus_start(b);
1281 int bus_set_address_system_remote(sd_bus *b, const char *host) {
1282 _cleanup_free_ char *e = NULL;
1283 char *m = NULL, *c = NULL;
1288 /* Let's see if we shall enter some container */
1289 m = strchr(host, ':');
1293 /* Let's make sure this is not a port of some kind,
1294 * and is a valid machine name. */
1295 if (!in_charset(m, "0123456789") && machine_name_is_valid(m)) {
1298 /* Cut out the host part */
1299 t = strndupa(host, m - host - 1);
1300 e = bus_address_escape(t);
1304 c = strjoina(",argv4=--machine=", m);
1309 e = bus_address_escape(host);
1314 b->address = strjoin("unixexec:path=ssh,argv1=-xT,argv2=", e, ",argv3=systemd-stdio-bridge", c, NULL);
1321 _public_ int sd_bus_open_system_remote(sd_bus **ret, const char *host) {
1325 assert_return(host, -EINVAL);
1326 assert_return(ret, -EINVAL);
1328 r = sd_bus_new(&bus);
1332 r = bus_set_address_system_remote(bus, host);
1336 bus->bus_client = true;
1337 bus->trusted = false;
1338 bus->is_system = true;
1340 r = sd_bus_start(bus);
1352 int bus_set_address_system_machine(sd_bus *b, const char *machine) {
1353 _cleanup_free_ char *e = NULL;
1358 e = bus_address_escape(machine);
1363 b->address = strjoin("x-machine-kernel:machine=", e, ";x-machine-unix:machine=", e, NULL);
1365 b->address = strjoin("x-machine-unix:machine=", e, NULL);
1373 _public_ int sd_bus_open_system_machine(sd_bus **ret, const char *machine) {
1377 assert_return(machine, -EINVAL);
1378 assert_return(ret, -EINVAL);
1379 assert_return(machine_name_is_valid(machine), -EINVAL);
1381 r = sd_bus_new(&bus);
1385 r = bus_set_address_system_machine(bus, machine);
1389 bus->bus_client = true;
1390 bus->trusted = false;
1391 bus->is_system = true;
1393 r = sd_bus_start(bus);
1405 _public_ void sd_bus_close(sd_bus *bus) {
1409 if (bus->state == BUS_CLOSED)
1411 if (bus_pid_changed(bus))
1414 bus->state = BUS_CLOSED;
1416 sd_bus_detach_event(bus);
1418 /* Drop all queued messages so that they drop references to
1419 * the bus object and the bus may be freed */
1420 bus_reset_queues(bus);
1422 if (!bus->is_kernel)
1425 /* We'll leave the fd open in case this is a kernel bus, since
1426 * there might still be memblocks around that reference this
1427 * bus, and they might need to invoke the KDBUS_CMD_FREE
1428 * ioctl on the fd when they are freed. */
1431 static void bus_enter_closing(sd_bus *bus) {
1434 if (bus->state != BUS_OPENING &&
1435 bus->state != BUS_AUTHENTICATING &&
1436 bus->state != BUS_HELLO &&
1437 bus->state != BUS_RUNNING)
1440 bus->state = BUS_CLOSING;
1443 _public_ sd_bus *sd_bus_ref(sd_bus *bus) {
1444 assert_return(bus, NULL);
1446 assert_se(REFCNT_INC(bus->n_ref) >= 2);
1451 _public_ sd_bus *sd_bus_unref(sd_bus *bus) {
1457 i = REFCNT_DEC(bus->n_ref);
1465 _public_ int sd_bus_is_open(sd_bus *bus) {
1467 assert_return(bus, -EINVAL);
1468 assert_return(!bus_pid_changed(bus), -ECHILD);
1470 return BUS_IS_OPEN(bus->state);
1473 _public_ int sd_bus_can_send(sd_bus *bus, char type) {
1476 assert_return(bus, -EINVAL);
1477 assert_return(bus->state != BUS_UNSET, -ENOTCONN);
1478 assert_return(!bus_pid_changed(bus), -ECHILD);
1480 if (bus->hello_flags & KDBUS_HELLO_MONITOR)
1483 if (type == SD_BUS_TYPE_UNIX_FD) {
1484 if (!(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD))
1487 r = bus_ensure_running(bus);
1491 return bus->can_fds;
1494 return bus_type_is_valid(type);
1497 _public_ int sd_bus_get_bus_id(sd_bus *bus, sd_id128_t *id) {
1500 assert_return(bus, -EINVAL);
1501 assert_return(id, -EINVAL);
1502 assert_return(!bus_pid_changed(bus), -ECHILD);
1504 r = bus_ensure_running(bus);
1508 *id = bus->server_id;
1512 static int bus_seal_message(sd_bus *b, sd_bus_message *m, usec_t timeout) {
1517 /* If we copy the same message to multiple
1518 * destinations, avoid using the same cookie
1520 b->cookie = MAX(b->cookie, BUS_MESSAGE_COOKIE(m));
1525 timeout = BUS_DEFAULT_TIMEOUT;
1527 return bus_message_seal(m, ++b->cookie, timeout);
1530 static int bus_remarshal_message(sd_bus *b, sd_bus_message **m) {
1533 /* Do packet version and endianness already match? */
1534 if ((b->message_version == 0 || b->message_version == (*m)->header->version) &&
1535 (b->message_endian == 0 || b->message_endian == (*m)->header->endian))
1538 /* No? Then remarshal! */
1539 return bus_message_remarshal(b, m);
1542 int bus_seal_synthetic_message(sd_bus *b, sd_bus_message *m) {
1546 /* Fake some timestamps, if they were requested, and not
1547 * already initialized */
1548 if (b->attach_flags & KDBUS_ATTACH_TIMESTAMP) {
1549 if (m->realtime <= 0)
1550 m->realtime = now(CLOCK_REALTIME);
1552 if (m->monotonic <= 0)
1553 m->monotonic = now(CLOCK_MONOTONIC);
1556 /* The bus specification says the serial number cannot be 0,
1557 * hence let's fill something in for synthetic messages. Since
1558 * synthetic messages might have a fake sender and we don't
1559 * want to interfere with the real sender's serial numbers we
1560 * pick a fixed, artificial one. We use (uint32_t) -1 rather
1561 * than (uint64_t) -1 since dbus1 only had 32bit identifiers,
1562 * even though kdbus can do 64bit. */
1563 return bus_message_seal(m, 0xFFFFFFFFULL, 0);
1566 static int bus_write_message(sd_bus *bus, sd_bus_message *m, bool hint_sync_call, size_t *idx) {
1573 r = bus_kernel_write_message(bus, m, hint_sync_call);
1575 r = bus_socket_write_message(bus, m, idx);
1580 if (bus->is_kernel || *idx >= BUS_MESSAGE_SIZE(m))
1581 log_debug("Sent message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%" PRIu64 " reply_cookie=%" PRIu64 " error=%s",
1582 bus_message_type_to_string(m->header->type),
1583 strna(sd_bus_message_get_sender(m)),
1584 strna(sd_bus_message_get_destination(m)),
1585 strna(sd_bus_message_get_path(m)),
1586 strna(sd_bus_message_get_interface(m)),
1587 strna(sd_bus_message_get_member(m)),
1588 BUS_MESSAGE_COOKIE(m),
1590 strna(m->error.message));
1595 static int dispatch_wqueue(sd_bus *bus) {
1599 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1601 while (bus->wqueue_size > 0) {
1603 r = bus_write_message(bus, bus->wqueue[0], false, &bus->windex);
1607 /* Didn't do anything this time */
1609 else if (bus->is_kernel || bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
1610 /* Fully written. Let's drop the entry from
1613 * This isn't particularly optimized, but
1614 * well, this is supposed to be our worst-case
1615 * buffer only, and the socket buffer is
1616 * supposed to be our primary buffer, and if
1617 * it got full, then all bets are off
1620 bus->wqueue_size --;
1621 sd_bus_message_unref(bus->wqueue[0]);
1622 memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
1632 static int bus_read_message(sd_bus *bus, bool hint_priority, int64_t priority) {
1636 return bus_kernel_read_message(bus, hint_priority, priority);
1638 return bus_socket_read_message(bus);
1641 int bus_rqueue_make_room(sd_bus *bus) {
1644 if (bus->rqueue_size >= BUS_RQUEUE_MAX)
1647 if (!GREEDY_REALLOC(bus->rqueue, bus->rqueue_allocated, bus->rqueue_size + 1))
1653 static int dispatch_rqueue(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **m) {
1658 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1660 /* Note that the priority logic is only available on kdbus,
1661 * where the rqueue is unused. We check the rqueue here
1662 * anyway, because it's simple... */
1665 if (bus->rqueue_size > 0) {
1666 /* Dispatch a queued message */
1668 *m = bus->rqueue[0];
1669 bus->rqueue_size --;
1670 memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
1674 /* Try to read a new message */
1675 r = bus_read_message(bus, hint_priority, priority);
1685 static int bus_send_internal(sd_bus *bus, sd_bus_message *_m, uint64_t *cookie, bool hint_sync_call) {
1686 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1689 assert_return(bus, -EINVAL);
1690 assert_return(m, -EINVAL);
1691 assert_return(!bus_pid_changed(bus), -ECHILD);
1692 assert_return(!bus->is_kernel || !(bus->hello_flags & KDBUS_HELLO_MONITOR), -EROFS);
1694 if (!BUS_IS_OPEN(bus->state))
1698 r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
1705 /* If the cookie number isn't kept, then we know that no reply
1707 if (!cookie && !m->sealed)
1708 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1710 r = bus_seal_message(bus, m, 0);
1714 /* Remarshall if we have to. This will possibly unref the
1715 * message and place a replacement in m */
1716 r = bus_remarshal_message(bus, &m);
1720 /* If this is a reply and no reply was requested, then let's
1721 * suppress this, if we can */
1725 if ((bus->state == BUS_RUNNING || bus->state == BUS_HELLO) && bus->wqueue_size <= 0) {
1728 r = bus_write_message(bus, m, hint_sync_call, &idx);
1730 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
1731 bus_enter_closing(bus);
1738 if (!bus->is_kernel && idx < BUS_MESSAGE_SIZE(m)) {
1739 /* Wasn't fully written. So let's remember how
1740 * much was written. Note that the first entry
1741 * of the wqueue array is always allocated so
1742 * that we always can remember how much was
1744 bus->wqueue[0] = sd_bus_message_ref(m);
1745 bus->wqueue_size = 1;
1750 /* Just append it to the queue. */
1752 if (bus->wqueue_size >= BUS_WQUEUE_MAX)
1755 if (!GREEDY_REALLOC(bus->wqueue, bus->wqueue_allocated, bus->wqueue_size + 1))
1758 bus->wqueue[bus->wqueue_size ++] = sd_bus_message_ref(m);
1763 *cookie = BUS_MESSAGE_COOKIE(m);
1768 _public_ int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *cookie) {
1769 return bus_send_internal(bus, m, cookie, false);
1772 _public_ int sd_bus_send_to(sd_bus *bus, sd_bus_message *m, const char *destination, uint64_t *cookie) {
1775 assert_return(bus, -EINVAL);
1776 assert_return(m, -EINVAL);
1777 assert_return(!bus_pid_changed(bus), -ECHILD);
1779 if (!BUS_IS_OPEN(bus->state))
1782 if (!streq_ptr(m->destination, destination)) {
1787 r = sd_bus_message_set_destination(m, destination);
1792 return sd_bus_send(bus, m, cookie);
1795 static usec_t calc_elapse(uint64_t usec) {
1796 if (usec == (uint64_t) -1)
1799 return now(CLOCK_MONOTONIC) + usec;
1802 static int timeout_compare(const void *a, const void *b) {
1803 const struct reply_callback *x = a, *y = b;
1805 if (x->timeout != 0 && y->timeout == 0)
1808 if (x->timeout == 0 && y->timeout != 0)
1811 if (x->timeout < y->timeout)
1814 if (x->timeout > y->timeout)
1820 _public_ int sd_bus_call_async(
1824 sd_bus_message_handler_t callback,
1828 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1829 _cleanup_bus_slot_unref_ sd_bus_slot *s = NULL;
1832 assert_return(bus, -EINVAL);
1833 assert_return(m, -EINVAL);
1834 assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1835 assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1836 assert_return(callback, -EINVAL);
1837 assert_return(!bus_pid_changed(bus), -ECHILD);
1838 assert_return(!bus->is_kernel || !(bus->hello_flags & KDBUS_HELLO_MONITOR), -EROFS);
1840 if (!BUS_IS_OPEN(bus->state))
1843 r = ordered_hashmap_ensure_allocated(&bus->reply_callbacks, &uint64_hash_ops);
1847 r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
1851 r = bus_seal_message(bus, m, usec);
1855 r = bus_remarshal_message(bus, &m);
1859 s = bus_slot_allocate(bus, !slot, BUS_REPLY_CALLBACK, sizeof(struct reply_callback), userdata);
1863 s->reply_callback.callback = callback;
1865 s->reply_callback.cookie = BUS_MESSAGE_COOKIE(m);
1866 r = ordered_hashmap_put(bus->reply_callbacks, &s->reply_callback.cookie, &s->reply_callback);
1868 s->reply_callback.cookie = 0;
1872 s->reply_callback.timeout = calc_elapse(m->timeout);
1873 if (s->reply_callback.timeout != 0) {
1874 r = prioq_put(bus->reply_callbacks_prioq, &s->reply_callback, &s->reply_callback.prioq_idx);
1876 s->reply_callback.timeout = 0;
1881 r = sd_bus_send(bus, m, &s->reply_callback.cookie);
1892 int bus_ensure_running(sd_bus *bus) {
1897 if (bus->state == BUS_UNSET || bus->state == BUS_CLOSED || bus->state == BUS_CLOSING)
1899 if (bus->state == BUS_RUNNING)
1903 r = sd_bus_process(bus, NULL);
1906 if (bus->state == BUS_RUNNING)
1911 r = sd_bus_wait(bus, (uint64_t) -1);
1917 _public_ int sd_bus_call(
1921 sd_bus_error *error,
1922 sd_bus_message **reply) {
1924 _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1930 assert_return(bus, -EINVAL);
1931 assert_return(m, -EINVAL);
1932 assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1933 assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1934 assert_return(!bus_error_is_dirty(error), -EINVAL);
1935 assert_return(!bus_pid_changed(bus), -ECHILD);
1936 assert_return(!bus->is_kernel || !(bus->hello_flags & KDBUS_HELLO_MONITOR), -EROFS);
1938 if (!BUS_IS_OPEN(bus->state))
1941 r = bus_ensure_running(bus);
1945 i = bus->rqueue_size;
1947 r = bus_seal_message(bus, m, usec);
1951 r = bus_remarshal_message(bus, &m);
1955 r = bus_send_internal(bus, m, &cookie, true);
1959 timeout = calc_elapse(m->timeout);
1964 while (i < bus->rqueue_size) {
1965 sd_bus_message *incoming = NULL;
1967 incoming = bus->rqueue[i];
1969 if (incoming->reply_cookie == cookie) {
1970 /* Found a match! */
1972 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1975 if (incoming->header->type == SD_BUS_MESSAGE_METHOD_RETURN) {
1977 if (incoming->n_fds <= 0 || (bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)) {
1981 sd_bus_message_unref(incoming);
1986 r = sd_bus_error_setf(error, SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Reply message contained file descriptors which I couldn't accept. Sorry.");
1988 } else if (incoming->header->type == SD_BUS_MESSAGE_METHOD_ERROR)
1989 r = sd_bus_error_copy(error, &incoming->error);
1993 sd_bus_message_unref(incoming);
1996 } else if (BUS_MESSAGE_COOKIE(incoming) == cookie &&
1999 streq(bus->unique_name, incoming->sender)) {
2001 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
2004 /* Our own message? Somebody is trying
2005 * to send its own client a message,
2006 * let's not dead-lock, let's fail
2009 sd_bus_message_unref(incoming);
2013 /* Try to read more, right-away */
2017 r = bus_read_message(bus, false, 0);
2019 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2020 bus_enter_closing(bus);
2032 n = now(CLOCK_MONOTONIC);
2038 left = (uint64_t) -1;
2040 r = bus_poll(bus, true, left);
2046 r = dispatch_wqueue(bus);
2048 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2049 bus_enter_closing(bus);
2058 _public_ int sd_bus_get_fd(sd_bus *bus) {
2060 assert_return(bus, -EINVAL);
2061 assert_return(bus->input_fd == bus->output_fd, -EPERM);
2062 assert_return(!bus_pid_changed(bus), -ECHILD);
2064 return bus->input_fd;
2067 _public_ int sd_bus_get_events(sd_bus *bus) {
2070 assert_return(bus, -EINVAL);
2071 assert_return(!bus_pid_changed(bus), -ECHILD);
2073 if (!BUS_IS_OPEN(bus->state) && bus->state != BUS_CLOSING)
2076 if (bus->state == BUS_OPENING)
2078 else if (bus->state == BUS_AUTHENTICATING) {
2080 if (bus_socket_auth_needs_write(bus))
2085 } else if (bus->state == BUS_RUNNING || bus->state == BUS_HELLO) {
2086 if (bus->rqueue_size <= 0)
2088 if (bus->wqueue_size > 0)
2095 _public_ int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
2096 struct reply_callback *c;
2098 assert_return(bus, -EINVAL);
2099 assert_return(timeout_usec, -EINVAL);
2100 assert_return(!bus_pid_changed(bus), -ECHILD);
2102 if (!BUS_IS_OPEN(bus->state) && bus->state != BUS_CLOSING)
2105 if (bus->track_queue) {
2110 if (bus->state == BUS_CLOSING) {
2115 if (bus->state == BUS_AUTHENTICATING) {
2116 *timeout_usec = bus->auth_timeout;
2120 if (bus->state != BUS_RUNNING && bus->state != BUS_HELLO) {
2121 *timeout_usec = (uint64_t) -1;
2125 if (bus->rqueue_size > 0) {
2130 c = prioq_peek(bus->reply_callbacks_prioq);
2132 *timeout_usec = (uint64_t) -1;
2136 if (c->timeout == 0) {
2137 *timeout_usec = (uint64_t) -1;
2141 *timeout_usec = c->timeout;
2145 static int process_timeout(sd_bus *bus) {
2146 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2147 _cleanup_bus_message_unref_ sd_bus_message* m = NULL;
2148 struct reply_callback *c;
2155 c = prioq_peek(bus->reply_callbacks_prioq);
2159 n = now(CLOCK_MONOTONIC);
2163 r = bus_message_new_synthetic_error(
2166 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
2171 r = bus_seal_synthetic_message(bus, m);
2175 assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
2178 ordered_hashmap_remove(bus->reply_callbacks, &c->cookie);
2181 slot = container_of(c, sd_bus_slot, reply_callback);
2183 bus->iteration_counter ++;
2185 bus->current_message = m;
2186 bus->current_slot = sd_bus_slot_ref(slot);
2187 bus->current_handler = c->callback;
2188 bus->current_userdata = slot->userdata;
2189 r = c->callback(bus, m, slot->userdata, &error_buffer);
2190 bus->current_userdata = NULL;
2191 bus->current_handler = NULL;
2192 bus->current_slot = NULL;
2193 bus->current_message = NULL;
2195 if (slot->floating) {
2196 bus_slot_disconnect(slot);
2197 sd_bus_slot_unref(slot);
2200 sd_bus_slot_unref(slot);
2202 return bus_maybe_reply_error(m, r, &error_buffer);
2205 static int process_hello(sd_bus *bus, sd_bus_message *m) {
2209 if (bus->state != BUS_HELLO)
2212 /* Let's make sure the first message on the bus is the HELLO
2213 * reply. But note that we don't actually parse the message
2214 * here (we leave that to the usual handling), we just verify
2215 * we don't let any earlier msg through. */
2217 if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2218 m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2221 if (m->reply_cookie != 1)
2227 static int process_reply(sd_bus *bus, sd_bus_message *m) {
2228 _cleanup_bus_message_unref_ sd_bus_message *synthetic_reply = NULL;
2229 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2230 struct reply_callback *c;
2237 if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2238 m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2241 if (bus->is_kernel && (bus->hello_flags & KDBUS_HELLO_MONITOR))
2244 if (m->destination && bus->unique_name && !streq_ptr(m->destination, bus->unique_name))
2247 c = ordered_hashmap_remove(bus->reply_callbacks, &m->reply_cookie);
2253 slot = container_of(c, sd_bus_slot, reply_callback);
2255 if (m->n_fds > 0 && !(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)) {
2257 /* If the reply contained a file descriptor which we
2258 * didn't want we pass an error instead. */
2260 r = bus_message_new_synthetic_error(
2263 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Reply message contained file descriptor"),
2268 /* Copy over original timestamp */
2269 synthetic_reply->realtime = m->realtime;
2270 synthetic_reply->monotonic = m->monotonic;
2271 synthetic_reply->seqnum = m->seqnum;
2273 r = bus_seal_synthetic_message(bus, synthetic_reply);
2277 m = synthetic_reply;
2279 r = sd_bus_message_rewind(m, true);
2284 if (c->timeout != 0) {
2285 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2289 bus->current_slot = sd_bus_slot_ref(slot);
2290 bus->current_handler = c->callback;
2291 bus->current_userdata = slot->userdata;
2292 r = c->callback(bus, m, slot->userdata, &error_buffer);
2293 bus->current_userdata = NULL;
2294 bus->current_handler = NULL;
2295 bus->current_slot = NULL;
2297 if (slot->floating) {
2298 bus_slot_disconnect(slot);
2299 sd_bus_slot_unref(slot);
2302 sd_bus_slot_unref(slot);
2304 return bus_maybe_reply_error(m, r, &error_buffer);
2307 static int process_filter(sd_bus *bus, sd_bus_message *m) {
2308 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2309 struct filter_callback *l;
2316 bus->filter_callbacks_modified = false;
2318 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
2321 if (bus->filter_callbacks_modified)
2324 /* Don't run this more than once per iteration */
2325 if (l->last_iteration == bus->iteration_counter)
2328 l->last_iteration = bus->iteration_counter;
2330 r = sd_bus_message_rewind(m, true);
2334 slot = container_of(l, sd_bus_slot, filter_callback);
2336 bus->current_slot = sd_bus_slot_ref(slot);
2337 bus->current_handler = l->callback;
2338 bus->current_userdata = slot->userdata;
2339 r = l->callback(bus, m, slot->userdata, &error_buffer);
2340 bus->current_userdata = NULL;
2341 bus->current_handler = NULL;
2342 bus->current_slot = sd_bus_slot_unref(slot);
2344 r = bus_maybe_reply_error(m, r, &error_buffer);
2350 } while (bus->filter_callbacks_modified);
2355 static int process_match(sd_bus *bus, sd_bus_message *m) {
2362 bus->match_callbacks_modified = false;
2364 r = bus_match_run(bus, &bus->match_callbacks, m);
2368 } while (bus->match_callbacks_modified);
2373 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
2374 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2380 if (bus->hello_flags & KDBUS_HELLO_MONITOR)
2383 if (bus->manual_peer_interface)
2386 if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2389 if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2392 if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2395 if (streq_ptr(m->member, "Ping"))
2396 r = sd_bus_message_new_method_return(m, &reply);
2397 else if (streq_ptr(m->member, "GetMachineId")) {
2401 r = sd_id128_get_machine(&id);
2405 r = sd_bus_message_new_method_return(m, &reply);
2409 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2411 r = sd_bus_message_new_method_errorf(
2413 SD_BUS_ERROR_UNKNOWN_METHOD,
2414 "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2420 r = sd_bus_send(bus, reply, NULL);
2427 static int process_fd_check(sd_bus *bus, sd_bus_message *m) {
2431 /* If we got a message with a file descriptor which we didn't
2432 * want to accept, then let's drop it. How can this even
2433 * happen? For example, when the kernel queues a message into
2434 * an activatable names's queue which allows fds, and then is
2435 * delivered to us later even though we ourselves did not
2438 if (bus->hello_flags & KDBUS_HELLO_MONITOR)
2444 if (bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)
2447 if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2448 return 1; /* just eat it up */
2450 return sd_bus_reply_method_errorf(m, SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Message contains file descriptors, which I cannot accept. Sorry.");
2453 static int process_message(sd_bus *bus, sd_bus_message *m) {
2459 bus->current_message = m;
2460 bus->iteration_counter++;
2462 log_debug("Got message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%" PRIu64 " reply_cookie=%" PRIu64 " error=%s",
2463 bus_message_type_to_string(m->header->type),
2464 strna(sd_bus_message_get_sender(m)),
2465 strna(sd_bus_message_get_destination(m)),
2466 strna(sd_bus_message_get_path(m)),
2467 strna(sd_bus_message_get_interface(m)),
2468 strna(sd_bus_message_get_member(m)),
2469 BUS_MESSAGE_COOKIE(m),
2471 strna(m->error.message));
2473 r = process_hello(bus, m);
2477 r = process_reply(bus, m);
2481 r = process_fd_check(bus, m);
2485 r = process_filter(bus, m);
2489 r = process_match(bus, m);
2493 r = process_builtin(bus, m);
2497 r = bus_process_object(bus, m);
2500 bus->current_message = NULL;
2504 static int dispatch_track(sd_bus *bus) {
2507 if (!bus->track_queue)
2510 bus_track_dispatch(bus->track_queue);
2514 static int process_running(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2515 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2519 assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
2521 r = process_timeout(bus);
2525 r = dispatch_wqueue(bus);
2529 r = dispatch_track(bus);
2533 r = dispatch_rqueue(bus, hint_priority, priority, &m);
2539 r = process_message(bus, m);
2544 r = sd_bus_message_rewind(m, true);
2553 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2555 log_debug("Unprocessed message call sender=%s object=%s interface=%s member=%s",
2556 strna(sd_bus_message_get_sender(m)),
2557 strna(sd_bus_message_get_path(m)),
2558 strna(sd_bus_message_get_interface(m)),
2559 strna(sd_bus_message_get_member(m)));
2561 r = sd_bus_reply_method_errorf(
2563 SD_BUS_ERROR_UNKNOWN_OBJECT,
2564 "Unknown object '%s'.", m->path);
2578 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2579 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2580 struct reply_callback *c;
2584 assert(bus->state == BUS_CLOSING);
2586 c = ordered_hashmap_first(bus->reply_callbacks);
2588 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2591 /* First, fail all outstanding method calls */
2592 r = bus_message_new_synthetic_error(
2595 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2600 r = bus_seal_synthetic_message(bus, m);
2604 if (c->timeout != 0) {
2605 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2609 ordered_hashmap_remove(bus->reply_callbacks, &c->cookie);
2612 slot = container_of(c, sd_bus_slot, reply_callback);
2614 bus->iteration_counter++;
2616 bus->current_message = m;
2617 bus->current_slot = sd_bus_slot_ref(slot);
2618 bus->current_handler = c->callback;
2619 bus->current_userdata = slot->userdata;
2620 r = c->callback(bus, m, slot->userdata, &error_buffer);
2621 bus->current_userdata = NULL;
2622 bus->current_handler = NULL;
2623 bus->current_slot = NULL;
2624 bus->current_message = NULL;
2626 if (slot->floating) {
2627 bus_slot_disconnect(slot);
2628 sd_bus_slot_unref(slot);
2631 sd_bus_slot_unref(slot);
2633 return bus_maybe_reply_error(m, r, &error_buffer);
2636 /* Then, synthesize a Disconnected message */
2637 r = sd_bus_message_new_signal(
2640 "/org/freedesktop/DBus/Local",
2641 "org.freedesktop.DBus.Local",
2646 bus_message_set_sender_local(bus, m);
2648 r = bus_seal_synthetic_message(bus, m);
2654 bus->current_message = m;
2655 bus->iteration_counter++;
2657 r = process_filter(bus, m);
2661 r = process_match(bus, m);
2673 bus->current_message = NULL;
2678 static int bus_process_internal(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2679 BUS_DONT_DESTROY(bus);
2682 /* Returns 0 when we didn't do anything. This should cause the
2683 * caller to invoke sd_bus_wait() before returning the next
2684 * time. Returns > 0 when we did something, which possibly
2685 * means *ret is filled in with an unprocessed message. */
2687 assert_return(bus, -EINVAL);
2688 assert_return(!bus_pid_changed(bus), -ECHILD);
2690 /* We don't allow recursively invoking sd_bus_process(). */
2691 assert_return(!bus->current_message, -EBUSY);
2692 assert(!bus->current_slot);
2694 switch (bus->state) {
2703 r = bus_socket_process_opening(bus);
2704 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2705 bus_enter_closing(bus);
2713 case BUS_AUTHENTICATING:
2714 r = bus_socket_process_authenticating(bus);
2715 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2716 bus_enter_closing(bus);
2728 r = process_running(bus, hint_priority, priority, ret);
2729 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2730 bus_enter_closing(bus);
2740 return process_closing(bus, ret);
2743 assert_not_reached("Unknown state");
2746 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2747 return bus_process_internal(bus, false, 0, ret);
2750 _public_ int sd_bus_process_priority(sd_bus *bus, int64_t priority, sd_bus_message **ret) {
2751 return bus_process_internal(bus, true, priority, ret);
2754 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2755 struct pollfd p[2] = {};
2758 usec_t m = USEC_INFINITY;
2762 if (bus->state == BUS_CLOSING)
2765 if (!BUS_IS_OPEN(bus->state))
2768 e = sd_bus_get_events(bus);
2773 /* The caller really needs some more data, he doesn't
2774 * care about what's already read, or any timeouts
2775 * except its own. */
2779 /* The caller wants to process if there's something to
2780 * process, but doesn't care otherwise */
2782 r = sd_bus_get_timeout(bus, &until);
2787 nw = now(CLOCK_MONOTONIC);
2788 m = until > nw ? until - nw : 0;
2792 if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
2795 p[0].fd = bus->input_fd;
2796 if (bus->output_fd == bus->input_fd) {
2800 p[0].events = e & POLLIN;
2801 p[1].fd = bus->output_fd;
2802 p[1].events = e & POLLOUT;
2806 r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
2810 return r > 0 ? 1 : 0;
2813 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
2815 assert_return(bus, -EINVAL);
2816 assert_return(!bus_pid_changed(bus), -ECHILD);
2818 if (bus->state == BUS_CLOSING)
2821 if (!BUS_IS_OPEN(bus->state))
2824 if (bus->rqueue_size > 0)
2827 return bus_poll(bus, false, timeout_usec);
2830 _public_ int sd_bus_flush(sd_bus *bus) {
2833 assert_return(bus, -EINVAL);
2834 assert_return(!bus_pid_changed(bus), -ECHILD);
2836 if (bus->state == BUS_CLOSING)
2839 if (!BUS_IS_OPEN(bus->state))
2842 r = bus_ensure_running(bus);
2846 if (bus->wqueue_size <= 0)
2850 r = dispatch_wqueue(bus);
2852 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2853 bus_enter_closing(bus);
2860 if (bus->wqueue_size <= 0)
2863 r = bus_poll(bus, false, (uint64_t) -1);
2869 _public_ int sd_bus_add_filter(
2872 sd_bus_message_handler_t callback,
2877 assert_return(bus, -EINVAL);
2878 assert_return(callback, -EINVAL);
2879 assert_return(!bus_pid_changed(bus), -ECHILD);
2881 s = bus_slot_allocate(bus, !slot, BUS_FILTER_CALLBACK, sizeof(struct filter_callback), userdata);
2885 s->filter_callback.callback = callback;
2887 bus->filter_callbacks_modified = true;
2888 LIST_PREPEND(callbacks, bus->filter_callbacks, &s->filter_callback);
2896 _public_ int sd_bus_add_match(
2900 sd_bus_message_handler_t callback,
2903 struct bus_match_component *components = NULL;
2904 unsigned n_components = 0;
2905 sd_bus_slot *s = NULL;
2908 assert_return(bus, -EINVAL);
2909 assert_return(match, -EINVAL);
2910 assert_return(!bus_pid_changed(bus), -ECHILD);
2912 r = bus_match_parse(match, &components, &n_components);
2916 s = bus_slot_allocate(bus, !slot, BUS_MATCH_CALLBACK, sizeof(struct match_callback), userdata);
2922 s->match_callback.callback = callback;
2923 s->match_callback.cookie = ++bus->match_cookie;
2925 if (bus->bus_client) {
2927 if (!bus->is_kernel) {
2928 /* When this is not a kernel transport, we
2929 * store the original match string, so that we
2930 * can use it to remove the match again */
2932 s->match_callback.match_string = strdup(match);
2933 if (!s->match_callback.match_string) {
2939 r = bus_add_match_internal(bus, s->match_callback.match_string, components, n_components, s->match_callback.cookie);
2944 bus->match_callbacks_modified = true;
2945 r = bus_match_add(&bus->match_callbacks, components, n_components, &s->match_callback);
2954 bus_match_parse_free(components, n_components);
2955 sd_bus_slot_unref(s);
2960 int bus_remove_match_by_string(
2963 sd_bus_message_handler_t callback,
2966 struct bus_match_component *components = NULL;
2967 unsigned n_components = 0;
2968 struct match_callback *c;
2971 assert_return(bus, -EINVAL);
2972 assert_return(match, -EINVAL);
2973 assert_return(!bus_pid_changed(bus), -ECHILD);
2975 r = bus_match_parse(match, &components, &n_components);
2979 r = bus_match_find(&bus->match_callbacks, components, n_components, NULL, NULL, &c);
2983 sd_bus_slot_unref(container_of(c, sd_bus_slot, match_callback));
2986 bus_match_parse_free(components, n_components);
2991 bool bus_pid_changed(sd_bus *bus) {
2994 /* We don't support people creating a bus connection and
2995 * keeping it around over a fork(). Let's complain. */
2997 return bus->original_pid != getpid();
3000 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
3001 sd_bus *bus = userdata;
3006 r = sd_bus_process(bus, NULL);
3013 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
3014 sd_bus *bus = userdata;
3019 r = sd_bus_process(bus, NULL);
3026 static int prepare_callback(sd_event_source *s, void *userdata) {
3027 sd_bus *bus = userdata;
3034 e = sd_bus_get_events(bus);
3038 if (bus->output_fd != bus->input_fd) {
3040 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
3044 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
3048 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
3053 r = sd_bus_get_timeout(bus, &until);
3059 j = sd_event_source_set_time(bus->time_event_source, until);
3064 r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
3071 static int quit_callback(sd_event_source *event, void *userdata) {
3072 sd_bus *bus = userdata;
3082 static int attach_io_events(sd_bus *bus) {
3087 if (bus->input_fd < 0)
3093 if (!bus->input_io_event_source) {
3094 r = sd_event_add_io(bus->event, &bus->input_io_event_source, bus->input_fd, 0, io_callback, bus);
3098 r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
3102 r = sd_event_source_set_priority(bus->input_io_event_source, bus->event_priority);
3106 r = sd_event_source_set_description(bus->input_io_event_source, "bus-input");
3108 r = sd_event_source_set_io_fd(bus->input_io_event_source, bus->input_fd);
3113 if (bus->output_fd != bus->input_fd) {
3114 assert(bus->output_fd >= 0);
3116 if (!bus->output_io_event_source) {
3117 r = sd_event_add_io(bus->event, &bus->output_io_event_source, bus->output_fd, 0, io_callback, bus);
3121 r = sd_event_source_set_priority(bus->output_io_event_source, bus->event_priority);
3125 r = sd_event_source_set_description(bus->input_io_event_source, "bus-output");
3127 r = sd_event_source_set_io_fd(bus->output_io_event_source, bus->output_fd);
3136 static void detach_io_events(sd_bus *bus) {
3139 if (bus->input_io_event_source) {
3140 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
3141 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
3144 if (bus->output_io_event_source) {
3145 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
3146 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
3150 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
3153 assert_return(bus, -EINVAL);
3154 assert_return(!bus->event, -EBUSY);
3156 assert(!bus->input_io_event_source);
3157 assert(!bus->output_io_event_source);
3158 assert(!bus->time_event_source);
3161 bus->event = sd_event_ref(event);
3163 r = sd_event_default(&bus->event);
3168 bus->event_priority = priority;
3170 r = sd_event_add_time(bus->event, &bus->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, bus);
3174 r = sd_event_source_set_priority(bus->time_event_source, priority);
3178 r = sd_event_source_set_description(bus->time_event_source, "bus-time");
3182 r = sd_event_add_exit(bus->event, &bus->quit_event_source, quit_callback, bus);
3186 r = sd_event_source_set_description(bus->quit_event_source, "bus-exit");
3190 r = attach_io_events(bus);
3197 sd_bus_detach_event(bus);
3201 _public_ int sd_bus_detach_event(sd_bus *bus) {
3202 assert_return(bus, -EINVAL);
3207 detach_io_events(bus);
3209 if (bus->time_event_source) {
3210 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
3211 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
3214 if (bus->quit_event_source) {
3215 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
3216 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
3219 bus->event = sd_event_unref(bus->event);
3223 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
3224 assert_return(bus, NULL);
3229 _public_ sd_bus_message* sd_bus_get_current_message(sd_bus *bus) {
3230 assert_return(bus, NULL);
3232 return bus->current_message;
3235 _public_ sd_bus_slot* sd_bus_get_current_slot(sd_bus *bus) {
3236 assert_return(bus, NULL);
3238 return bus->current_slot;
3241 _public_ sd_bus_message_handler_t sd_bus_get_current_handler(sd_bus *bus) {
3242 assert_return(bus, NULL);
3244 return bus->current_handler;
3247 _public_ void* sd_bus_get_current_userdata(sd_bus *bus) {
3248 assert_return(bus, NULL);
3250 return bus->current_userdata;
3253 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
3258 assert(default_bus);
3261 return !!*default_bus;
3264 *ret = sd_bus_ref(*default_bus);
3272 b->default_bus_ptr = default_bus;
3280 _public_ int sd_bus_default_system(sd_bus **ret) {
3281 static thread_local sd_bus *default_system_bus = NULL;
3283 return bus_default(sd_bus_open_system, &default_system_bus, ret);
3286 _public_ int sd_bus_default_user(sd_bus **ret) {
3287 static thread_local sd_bus *default_user_bus = NULL;
3289 return bus_default(sd_bus_open_user, &default_user_bus, ret);
3292 _public_ int sd_bus_default(sd_bus **ret) {
3296 /* Let's try our best to reuse another cached connection. If
3297 * the starter bus type is set, connect via our normal
3298 * connection logic, ignoring $DBUS_STARTER_ADDRESS, so that
3299 * we can share the connection with the user/system default
3302 e = secure_getenv("DBUS_STARTER_BUS_TYPE");
3304 if (streq(e, "system"))
3305 return sd_bus_default_system(ret);
3306 else if (STR_IN_SET(e, "user", "session"))
3307 return sd_bus_default_user(ret);
3310 /* No type is specified, so we have not other option than to
3311 * use the starter address if it is set. */
3313 e = secure_getenv("DBUS_STARTER_ADDRESS");
3315 static thread_local sd_bus *default_starter_bus = NULL;
3317 return bus_default(sd_bus_open, &default_starter_bus, ret);
3320 /* Finally, if nothing is set use the cached connection for
3321 * the right scope */
3323 if (cg_pid_get_owner_uid(0, NULL) >= 0)
3324 return sd_bus_default_user(ret);
3326 return sd_bus_default_system(ret);
3329 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
3330 assert_return(b, -EINVAL);
3331 assert_return(tid, -EINVAL);
3332 assert_return(!bus_pid_changed(b), -ECHILD);
3340 return sd_event_get_tid(b->event, tid);
3345 _public_ int sd_bus_path_encode(const char *prefix, const char *external_id, char **ret_path) {
3346 _cleanup_free_ char *e = NULL;
3349 assert_return(object_path_is_valid(prefix), -EINVAL);
3350 assert_return(external_id, -EINVAL);
3351 assert_return(ret_path, -EINVAL);
3353 e = bus_label_escape(external_id);
3357 ret = strjoin(prefix, "/", e, NULL);
3365 _public_ int sd_bus_path_decode(const char *path, const char *prefix, char **external_id) {
3369 assert_return(object_path_is_valid(path), -EINVAL);
3370 assert_return(object_path_is_valid(prefix), -EINVAL);
3371 assert_return(external_id, -EINVAL);
3373 e = object_path_startswith(path, prefix);
3375 *external_id = NULL;
3379 ret = bus_label_unescape(e);
3387 _public_ int sd_bus_try_close(sd_bus *bus) {
3390 assert_return(bus, -EINVAL);
3391 assert_return(!bus_pid_changed(bus), -ECHILD);
3393 if (!bus->is_kernel)
3396 if (!BUS_IS_OPEN(bus->state))
3399 if (bus->rqueue_size > 0)
3402 if (bus->wqueue_size > 0)
3405 r = bus_kernel_try_close(bus);
3413 _public_ int sd_bus_get_description(sd_bus *bus, const char **description) {
3414 assert_return(bus, -EINVAL);
3415 assert_return(description, -EINVAL);
3416 assert_return(bus->description, -ENXIO);
3417 assert_return(!bus_pid_changed(bus), -ECHILD);
3419 *description = bus->description;
3423 int bus_get_root_path(sd_bus *bus) {
3426 if (bus->cgroup_root)
3429 r = cg_get_root_path(&bus->cgroup_root);
3431 bus->cgroup_root = strdup("/");
3432 if (!bus->cgroup_root)
3441 _public_ int sd_bus_get_scope(sd_bus *bus, const char **scope) {
3444 assert_return(bus, -EINVAL);
3445 assert_return(scope, -EINVAL);
3446 assert_return(!bus_pid_changed(bus), -ECHILD);
3448 if (bus->is_kernel) {
3449 _cleanup_free_ char *n = NULL;
3452 r = bus_kernel_get_bus_name(bus, &n);
3456 if (streq(n, "0-system")) {
3461 dash = strchr(n, '-');
3462 if (streq_ptr(dash, "-user")) {
3473 if (bus->is_system) {
3481 _public_ int sd_bus_get_address(sd_bus *bus, const char **address) {
3483 assert_return(bus, -EINVAL);
3484 assert_return(address, -EINVAL);
3485 assert_return(!bus_pid_changed(bus), -ECHILD);
3488 *address = bus->address;
3495 int sd_bus_get_creds_mask(sd_bus *bus, uint64_t *mask) {
3496 assert_return(bus, -EINVAL);
3497 assert_return(mask, -EINVAL);
3498 assert_return(!bus_pid_changed(bus), -ECHILD);
3500 *mask = bus->creds_mask;
3504 int sd_bus_is_bus_client(sd_bus *bus) {
3505 assert_return(bus, -EINVAL);
3506 assert_return(!bus_pid_changed(bus), -ECHILD);
3508 return bus->bus_client;
3511 int sd_bus_is_server(sd_bus *bus) {
3512 assert_return(bus, -EINVAL);
3513 assert_return(!bus_pid_changed(bus), -ECHILD);
3515 return bus->is_server;
3518 int sd_bus_is_anonymous(sd_bus *bus) {
3519 assert_return(bus, -EINVAL);
3520 assert_return(!bus_pid_changed(bus), -ECHILD);
3522 return bus->anonymous_auth;
3525 int sd_bus_is_trusted(sd_bus *bus) {
3526 assert_return(bus, -EINVAL);
3527 assert_return(!bus_pid_changed(bus), -ECHILD);
3529 return bus->trusted;
3532 int sd_bus_is_monitor(sd_bus *bus) {
3533 assert_return(bus, -EINVAL);
3534 assert_return(!bus_pid_changed(bus), -ECHILD);
3536 return !!(bus->hello_flags & KDBUS_HELLO_MONITOR);