chiark / gitweb /
630c84935f0f87f37270e0e07e00ea9b123e42b5
[elogind.git] / src / libelogind / sd-bus / sd-bus.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2013 Lennart Poettering
7
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.
12
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.
17
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/>.
20 ***/
21
22 #include <endian.h>
23 #include <netdb.h>
24 #include <poll.h>
25 #include <pthread.h>
26 #include <stdlib.h>
27 #include <sys/mman.h>
28 #include <unistd.h>
29
30 #include "sd-bus.h"
31
32 #include "alloc-util.h"
33 #include "bus-container.h"
34 #include "bus-control.h"
35 #include "bus-internal.h"
36 #include "bus-kernel.h"
37 #include "bus-label.h"
38 #include "bus-message.h"
39 #include "bus-objects.h"
40 #include "bus-protocol.h"
41 #include "bus-slot.h"
42 #include "bus-socket.h"
43 #include "bus-track.h"
44 #include "bus-type.h"
45 #include "bus-util.h"
46 #include "cgroup-util.h"
47 #include "def.h"
48 #include "fd-util.h"
49 #include "hexdecoct.h"
50 #include "hostname-util.h"
51 #include "macro.h"
52 #include "missing.h"
53 #include "parse-util.h"
54 #include "string-util.h"
55 #include "strv.h"
56 #include "util.h"
57
58 #define log_debug_bus_message(m)                                         \
59         do {                                                             \
60                 sd_bus_message *_mm = (m);                               \
61                 log_debug("Got message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%" PRIu64 " reply_cookie=%" PRIu64 " error=%s", \
62                           bus_message_type_to_string(_mm->header->type), \
63                           strna(sd_bus_message_get_sender(_mm)),         \
64                           strna(sd_bus_message_get_destination(_mm)),    \
65                           strna(sd_bus_message_get_path(_mm)),           \
66                           strna(sd_bus_message_get_interface(_mm)),      \
67                           strna(sd_bus_message_get_member(_mm)),         \
68                           BUS_MESSAGE_COOKIE(_mm),                       \
69                           _mm->reply_cookie,                             \
70                           strna(_mm->error.message));                    \
71         } while (false)
72
73 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec);
74 static int attach_io_events(sd_bus *b);
75 static void detach_io_events(sd_bus *b);
76
77 static thread_local sd_bus *default_system_bus = NULL;
78 /// UNNEEDED by elogind
79 #if 0
80 static thread_local sd_bus *default_user_bus = NULL;
81 #endif // 0
82 static thread_local sd_bus *default_starter_bus = NULL;
83
84 static void bus_close_fds(sd_bus *b) {
85         assert(b);
86
87         detach_io_events(b);
88
89         if (b->input_fd != b->output_fd)
90                 safe_close(b->output_fd);
91         b->output_fd = b->input_fd = safe_close(b->input_fd);
92 }
93
94 static void bus_reset_queues(sd_bus *b) {
95         assert(b);
96
97         while (b->rqueue_size > 0)
98                 sd_bus_message_unref(b->rqueue[--b->rqueue_size]);
99
100         b->rqueue = mfree(b->rqueue);
101         b->rqueue_allocated = 0;
102
103         while (b->wqueue_size > 0)
104                 sd_bus_message_unref(b->wqueue[--b->wqueue_size]);
105
106         b->wqueue = mfree(b->wqueue);
107         b->wqueue_allocated = 0;
108 }
109
110 static void bus_free(sd_bus *b) {
111         sd_bus_slot *s;
112
113         assert(b);
114         assert(!b->track_queue);
115
116         b->state = BUS_CLOSED;
117
118         sd_bus_detach_event(b);
119
120         while ((s = b->slots)) {
121                 /* At this point only floating slots can still be
122                  * around, because the non-floating ones keep a
123                  * reference to the bus, and we thus couldn't be
124                  * destructing right now... We forcibly disconnect the
125                  * slots here, so that they still can be referenced by
126                  * apps, but are dead. */
127
128                 assert(s->floating);
129                 bus_slot_disconnect(s);
130                 sd_bus_slot_unref(s);
131         }
132
133         if (b->default_bus_ptr)
134                 *b->default_bus_ptr = NULL;
135
136         bus_close_fds(b);
137
138         if (b->kdbus_buffer)
139                 munmap(b->kdbus_buffer, KDBUS_POOL_SIZE);
140
141         free(b->label);
142         free(b->rbuffer);
143         free(b->unique_name);
144         free(b->auth_buffer);
145         free(b->address);
146         free(b->kernel);
147         free(b->machine);
148         free(b->fake_label);
149         free(b->cgroup_root);
150         free(b->description);
151
152         free(b->exec_path);
153         strv_free(b->exec_argv);
154
155         close_many(b->fds, b->n_fds);
156         free(b->fds);
157
158         bus_reset_queues(b);
159
160         ordered_hashmap_free_free(b->reply_callbacks);
161         prioq_free(b->reply_callbacks_prioq);
162
163         assert(b->match_callbacks.type == BUS_MATCH_ROOT);
164         bus_match_free(&b->match_callbacks);
165
166         hashmap_free_free(b->vtable_methods);
167         hashmap_free_free(b->vtable_properties);
168
169         assert(hashmap_isempty(b->nodes));
170         hashmap_free(b->nodes);
171
172         bus_kernel_flush_memfd(b);
173
174         assert_se(pthread_mutex_destroy(&b->memfd_cache_mutex) == 0);
175
176         free(b);
177 }
178
179 _public_ int sd_bus_new(sd_bus **ret) {
180         sd_bus *r;
181
182         assert_return(ret, -EINVAL);
183
184         r = new0(sd_bus, 1);
185         if (!r)
186                 return -ENOMEM;
187
188         r->n_ref = REFCNT_INIT;
189         r->input_fd = r->output_fd = -1;
190         r->message_version = 1;
191         r->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
192         r->hello_flags |= KDBUS_HELLO_ACCEPT_FD;
193         r->attach_flags |= KDBUS_ATTACH_NAMES;
194         r->original_pid = getpid();
195
196         assert_se(pthread_mutex_init(&r->memfd_cache_mutex, NULL) == 0);
197
198         /* We guarantee that wqueue always has space for at least one
199          * entry */
200         if (!GREEDY_REALLOC(r->wqueue, r->wqueue_allocated, 1)) {
201                 free(r);
202                 return -ENOMEM;
203         }
204
205         *ret = r;
206         return 0;
207 }
208
209 _public_ int sd_bus_set_address(sd_bus *bus, const char *address) {
210         char *a;
211
212         assert_return(bus, -EINVAL);
213         assert_return(bus->state == BUS_UNSET, -EPERM);
214         assert_return(address, -EINVAL);
215         assert_return(!bus_pid_changed(bus), -ECHILD);
216
217         a = strdup(address);
218         if (!a)
219                 return -ENOMEM;
220
221         free(bus->address);
222         bus->address = a;
223
224         return 0;
225 }
226
227 _public_ int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd) {
228         assert_return(bus, -EINVAL);
229         assert_return(bus->state == BUS_UNSET, -EPERM);
230         assert_return(input_fd >= 0, -EBADF);
231         assert_return(output_fd >= 0, -EBADF);
232         assert_return(!bus_pid_changed(bus), -ECHILD);
233
234         bus->input_fd = input_fd;
235         bus->output_fd = output_fd;
236         return 0;
237 }
238
239 /// UNNEEDED by elogind
240 #if 0
241 _public_ int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]) {
242         char *p, **a;
243
244         assert_return(bus, -EINVAL);
245         assert_return(bus->state == BUS_UNSET, -EPERM);
246         assert_return(path, -EINVAL);
247         assert_return(!strv_isempty(argv), -EINVAL);
248         assert_return(!bus_pid_changed(bus), -ECHILD);
249
250         p = strdup(path);
251         if (!p)
252                 return -ENOMEM;
253
254         a = strv_copy(argv);
255         if (!a) {
256                 free(p);
257                 return -ENOMEM;
258         }
259
260         free(bus->exec_path);
261         strv_free(bus->exec_argv);
262
263         bus->exec_path = p;
264         bus->exec_argv = a;
265
266         return 0;
267 }
268
269 _public_ int sd_bus_set_bus_client(sd_bus *bus, int b) {
270         assert_return(bus, -EINVAL);
271         assert_return(bus->state == BUS_UNSET, -EPERM);
272         assert_return(!bus_pid_changed(bus), -ECHILD);
273
274         bus->bus_client = !!b;
275         return 0;
276 }
277
278 _public_ int sd_bus_set_monitor(sd_bus *bus, int b) {
279         assert_return(bus, -EINVAL);
280         assert_return(bus->state == BUS_UNSET, -EPERM);
281         assert_return(!bus_pid_changed(bus), -ECHILD);
282
283         SET_FLAG(bus->hello_flags, KDBUS_HELLO_MONITOR, b);
284         return 0;
285 }
286
287 _public_ int sd_bus_negotiate_fds(sd_bus *bus, int b) {
288         assert_return(bus, -EINVAL);
289         assert_return(bus->state == BUS_UNSET, -EPERM);
290         assert_return(!bus_pid_changed(bus), -ECHILD);
291
292         SET_FLAG(bus->hello_flags, KDBUS_HELLO_ACCEPT_FD, b);
293         return 0;
294 }
295
296 _public_ int sd_bus_negotiate_timestamp(sd_bus *bus, int b) {
297         uint64_t new_flags;
298         assert_return(bus, -EINVAL);
299         assert_return(!IN_SET(bus->state, BUS_CLOSING, BUS_CLOSED), -EPERM);
300         assert_return(!bus_pid_changed(bus), -ECHILD);
301
302         new_flags = bus->attach_flags;
303         SET_FLAG(new_flags, KDBUS_ATTACH_TIMESTAMP, b);
304
305         if (bus->attach_flags == new_flags)
306                 return 0;
307
308         bus->attach_flags = new_flags;
309         if (bus->state != BUS_UNSET && bus->is_kernel)
310                 bus_kernel_realize_attach_flags(bus);
311
312         return 0;
313 }
314
315 _public_ int sd_bus_negotiate_creds(sd_bus *bus, int b, uint64_t mask) {
316         uint64_t new_flags;
317
318         assert_return(bus, -EINVAL);
319         assert_return(mask <= _SD_BUS_CREDS_ALL, -EINVAL);
320         assert_return(!IN_SET(bus->state, BUS_CLOSING, BUS_CLOSED), -EPERM);
321         assert_return(!bus_pid_changed(bus), -ECHILD);
322
323         if (b)
324                 bus->creds_mask |= mask;
325         else
326                 bus->creds_mask &= ~mask;
327
328         /* The well knowns we need unconditionally, so that matches can work */
329         bus->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
330
331         /* Make sure we don't lose the timestamp flag */
332         new_flags = (bus->attach_flags & KDBUS_ATTACH_TIMESTAMP) | attach_flags_to_kdbus(bus->creds_mask);
333         if (bus->attach_flags == new_flags)
334                 return 0;
335
336         bus->attach_flags = new_flags;
337         if (bus->state != BUS_UNSET && bus->is_kernel)
338                 bus_kernel_realize_attach_flags(bus);
339
340         return 0;
341 }
342
343 _public_ int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id) {
344         assert_return(bus, -EINVAL);
345         assert_return(b || sd_id128_equal(server_id, SD_ID128_NULL), -EINVAL);
346         assert_return(bus->state == BUS_UNSET, -EPERM);
347         assert_return(!bus_pid_changed(bus), -ECHILD);
348
349         bus->is_server = !!b;
350         bus->server_id = server_id;
351         return 0;
352 }
353
354 _public_ int sd_bus_set_anonymous(sd_bus *bus, int b) {
355         assert_return(bus, -EINVAL);
356         assert_return(bus->state == BUS_UNSET, -EPERM);
357         assert_return(!bus_pid_changed(bus), -ECHILD);
358
359         bus->anonymous_auth = !!b;
360         return 0;
361 }
362
363 _public_ int sd_bus_set_trusted(sd_bus *bus, int b) {
364         assert_return(bus, -EINVAL);
365         assert_return(bus->state == BUS_UNSET, -EPERM);
366         assert_return(!bus_pid_changed(bus), -ECHILD);
367
368         bus->trusted = !!b;
369         return 0;
370 }
371
372 _public_ int sd_bus_set_description(sd_bus *bus, const char *description) {
373         assert_return(bus, -EINVAL);
374         assert_return(bus->state == BUS_UNSET, -EPERM);
375         assert_return(!bus_pid_changed(bus), -ECHILD);
376
377         return free_and_strdup(&bus->description, description);
378 }
379 #endif // 0
380
381 _public_ int sd_bus_set_allow_interactive_authorization(sd_bus *bus, int b) {
382         assert_return(bus, -EINVAL);
383         assert_return(!bus_pid_changed(bus), -ECHILD);
384
385         bus->allow_interactive_authorization = !!b;
386         return 0;
387 }
388
389 /// UNNEEDED by elogind
390 #if 0
391 _public_ int sd_bus_get_allow_interactive_authorization(sd_bus *bus) {
392         assert_return(bus, -EINVAL);
393         assert_return(!bus_pid_changed(bus), -ECHILD);
394
395         return bus->allow_interactive_authorization;
396 }
397 #endif // 0
398
399 static int hello_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
400         const char *s;
401         sd_bus *bus;
402         int r;
403
404         assert(reply);
405         bus = reply->bus;
406         assert(bus);
407         assert(bus->state == BUS_HELLO || bus->state == BUS_CLOSING);
408
409         r = sd_bus_message_get_errno(reply);
410         if (r > 0)
411                 return -r;
412
413         r = sd_bus_message_read(reply, "s", &s);
414         if (r < 0)
415                 return r;
416
417         if (!service_name_is_valid(s) || s[0] != ':')
418                 return -EBADMSG;
419
420         bus->unique_name = strdup(s);
421         if (!bus->unique_name)
422                 return -ENOMEM;
423
424         if (bus->state == BUS_HELLO)
425                 bus->state = BUS_RUNNING;
426
427         return 1;
428 }
429
430 static int bus_send_hello(sd_bus *bus) {
431         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
432         int r;
433
434         assert(bus);
435
436         if (!bus->bus_client || bus->is_kernel)
437                 return 0;
438
439         r = sd_bus_message_new_method_call(
440                         bus,
441                         &m,
442                         "org.freedesktop.DBus",
443                         "/org/freedesktop/DBus",
444                         "org.freedesktop.DBus",
445                         "Hello");
446         if (r < 0)
447                 return r;
448
449         return sd_bus_call_async(bus, NULL, m, hello_callback, NULL, 0);
450 }
451
452 int bus_start_running(sd_bus *bus) {
453         assert(bus);
454
455         if (bus->bus_client && !bus->is_kernel) {
456                 bus->state = BUS_HELLO;
457                 return 1;
458         }
459
460         bus->state = BUS_RUNNING;
461         return 1;
462 }
463
464 static int parse_address_key(const char **p, const char *key, char **value) {
465         size_t l, n = 0, allocated = 0;
466         const char *a;
467         char *r = NULL;
468
469         assert(p);
470         assert(*p);
471         assert(value);
472
473         if (key) {
474                 l = strlen(key);
475                 if (strncmp(*p, key, l) != 0)
476                         return 0;
477
478                 if ((*p)[l] != '=')
479                         return 0;
480
481                 if (*value)
482                         return -EINVAL;
483
484                 a = *p + l + 1;
485         } else
486                 a = *p;
487
488         while (*a != ';' && *a != ',' && *a != 0) {
489                 char c;
490
491                 if (*a == '%') {
492                         int x, y;
493
494                         x = unhexchar(a[1]);
495                         if (x < 0) {
496                                 free(r);
497                                 return x;
498                         }
499
500                         y = unhexchar(a[2]);
501                         if (y < 0) {
502                                 free(r);
503                                 return y;
504                         }
505
506                         c = (char) ((x << 4) | y);
507                         a += 3;
508                 } else {
509                         c = *a;
510                         a++;
511                 }
512
513                 if (!GREEDY_REALLOC(r, allocated, n + 2))
514                         return -ENOMEM;
515
516                 r[n++] = c;
517         }
518
519         if (!r) {
520                 r = strdup("");
521                 if (!r)
522                         return -ENOMEM;
523         } else
524                 r[n] = 0;
525
526         if (*a == ',')
527                 a++;
528
529         *p = a;
530
531         free(*value);
532         *value = r;
533
534         return 1;
535 }
536
537 static void skip_address_key(const char **p) {
538         assert(p);
539         assert(*p);
540
541         *p += strcspn(*p, ",");
542
543         if (**p == ',')
544                 (*p) ++;
545 }
546
547 static int parse_unix_address(sd_bus *b, const char **p, char **guid) {
548         _cleanup_free_ char *path = NULL, *abstract = NULL;
549         size_t l;
550         int r;
551
552         assert(b);
553         assert(p);
554         assert(*p);
555         assert(guid);
556
557         while (**p != 0 && **p != ';') {
558                 r = parse_address_key(p, "guid", guid);
559                 if (r < 0)
560                         return r;
561                 else if (r > 0)
562                         continue;
563
564                 r = parse_address_key(p, "path", &path);
565                 if (r < 0)
566                         return r;
567                 else if (r > 0)
568                         continue;
569
570                 r = parse_address_key(p, "abstract", &abstract);
571                 if (r < 0)
572                         return r;
573                 else if (r > 0)
574                         continue;
575
576                 skip_address_key(p);
577         }
578
579         if (!path && !abstract)
580                 return -EINVAL;
581
582         if (path && abstract)
583                 return -EINVAL;
584
585         if (path) {
586                 l = strlen(path);
587                 if (l > sizeof(b->sockaddr.un.sun_path))
588                         return -E2BIG;
589
590                 b->sockaddr.un.sun_family = AF_UNIX;
591                 strncpy(b->sockaddr.un.sun_path, path, sizeof(b->sockaddr.un.sun_path));
592                 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l;
593         } else if (abstract) {
594                 l = strlen(abstract);
595                 if (l > sizeof(b->sockaddr.un.sun_path) - 1)
596                         return -E2BIG;
597
598                 b->sockaddr.un.sun_family = AF_UNIX;
599                 b->sockaddr.un.sun_path[0] = 0;
600                 strncpy(b->sockaddr.un.sun_path+1, abstract, sizeof(b->sockaddr.un.sun_path)-1);
601                 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
602         }
603
604         return 0;
605 }
606
607 static int parse_tcp_address(sd_bus *b, const char **p, char **guid) {
608         _cleanup_free_ char *host = NULL, *port = NULL, *family = NULL;
609         int r;
610         struct addrinfo *result, hints = {
611                 .ai_socktype = SOCK_STREAM,
612                 .ai_flags = AI_ADDRCONFIG,
613         };
614
615         assert(b);
616         assert(p);
617         assert(*p);
618         assert(guid);
619
620         while (**p != 0 && **p != ';') {
621                 r = parse_address_key(p, "guid", guid);
622                 if (r < 0)
623                         return r;
624                 else if (r > 0)
625                         continue;
626
627                 r = parse_address_key(p, "host", &host);
628                 if (r < 0)
629                         return r;
630                 else if (r > 0)
631                         continue;
632
633                 r = parse_address_key(p, "port", &port);
634                 if (r < 0)
635                         return r;
636                 else if (r > 0)
637                         continue;
638
639                 r = parse_address_key(p, "family", &family);
640                 if (r < 0)
641                         return r;
642                 else if (r > 0)
643                         continue;
644
645                 skip_address_key(p);
646         }
647
648         if (!host || !port)
649                 return -EINVAL;
650
651         if (family) {
652                 if (streq(family, "ipv4"))
653                         hints.ai_family = AF_INET;
654                 else if (streq(family, "ipv6"))
655                         hints.ai_family = AF_INET6;
656                 else
657                         return -EINVAL;
658         }
659
660         r = getaddrinfo(host, port, &hints, &result);
661         if (r == EAI_SYSTEM)
662                 return -errno;
663         else if (r != 0)
664                 return -EADDRNOTAVAIL;
665
666         memcpy(&b->sockaddr, result->ai_addr, result->ai_addrlen);
667         b->sockaddr_size = result->ai_addrlen;
668
669         freeaddrinfo(result);
670
671         return 0;
672 }
673
674 static int parse_exec_address(sd_bus *b, const char **p, char **guid) {
675         char *path = NULL;
676         unsigned n_argv = 0, j;
677         char **argv = NULL;
678         size_t allocated = 0;
679         int r;
680
681         assert(b);
682         assert(p);
683         assert(*p);
684         assert(guid);
685
686         while (**p != 0 && **p != ';') {
687                 r = parse_address_key(p, "guid", guid);
688                 if (r < 0)
689                         goto fail;
690                 else if (r > 0)
691                         continue;
692
693                 r = parse_address_key(p, "path", &path);
694                 if (r < 0)
695                         goto fail;
696                 else if (r > 0)
697                         continue;
698
699                 if (startswith(*p, "argv")) {
700                         unsigned ul;
701
702                         errno = 0;
703                         ul = strtoul(*p + 4, (char**) p, 10);
704                         if (errno > 0 || **p != '=' || ul > 256) {
705                                 r = -EINVAL;
706                                 goto fail;
707                         }
708
709                         (*p) ++;
710
711                         if (ul >= n_argv) {
712                                 if (!GREEDY_REALLOC0(argv, allocated, ul + 2)) {
713                                         r = -ENOMEM;
714                                         goto fail;
715                                 }
716
717                                 n_argv = ul + 1;
718                         }
719
720                         r = parse_address_key(p, NULL, argv + ul);
721                         if (r < 0)
722                                 goto fail;
723
724                         continue;
725                 }
726
727                 skip_address_key(p);
728         }
729
730         if (!path) {
731                 r = -EINVAL;
732                 goto fail;
733         }
734
735         /* Make sure there are no holes in the array, with the
736          * exception of argv[0] */
737         for (j = 1; j < n_argv; j++)
738                 if (!argv[j]) {
739                         r = -EINVAL;
740                         goto fail;
741                 }
742
743         if (argv && argv[0] == NULL) {
744                 argv[0] = strdup(path);
745                 if (!argv[0]) {
746                         r = -ENOMEM;
747                         goto fail;
748                 }
749         }
750
751         b->exec_path = path;
752         b->exec_argv = argv;
753         return 0;
754
755 fail:
756         for (j = 0; j < n_argv; j++)
757                 free(argv[j]);
758
759         free(argv);
760         free(path);
761         return r;
762 }
763
764 static int parse_kernel_address(sd_bus *b, const char **p, char **guid) {
765         _cleanup_free_ char *path = NULL;
766         int r;
767
768         assert(b);
769         assert(p);
770         assert(*p);
771         assert(guid);
772
773         while (**p != 0 && **p != ';') {
774                 r = parse_address_key(p, "guid", guid);
775                 if (r < 0)
776                         return r;
777                 else if (r > 0)
778                         continue;
779
780                 r = parse_address_key(p, "path", &path);
781                 if (r < 0)
782                         return r;
783                 else if (r > 0)
784                         continue;
785
786                 skip_address_key(p);
787         }
788
789         if (!path)
790                 return -EINVAL;
791
792         free(b->kernel);
793         b->kernel = path;
794         path = NULL;
795
796         return 0;
797 }
798
799 static int parse_container_unix_address(sd_bus *b, const char **p, char **guid) {
800         _cleanup_free_ char *machine = NULL, *pid = NULL;
801         int r;
802
803         assert(b);
804         assert(p);
805         assert(*p);
806         assert(guid);
807
808         while (**p != 0 && **p != ';') {
809                 r = parse_address_key(p, "guid", guid);
810                 if (r < 0)
811                         return r;
812                 else if (r > 0)
813                         continue;
814
815                 r = parse_address_key(p, "machine", &machine);
816                 if (r < 0)
817                         return r;
818                 else if (r > 0)
819                         continue;
820
821                 r = parse_address_key(p, "pid", &pid);
822                 if (r < 0)
823                         return r;
824                 else if (r > 0)
825                         continue;
826
827                 skip_address_key(p);
828         }
829
830         if (!machine == !pid)
831                 return -EINVAL;
832
833         if (machine) {
834                 if (!machine_name_is_valid(machine))
835                         return -EINVAL;
836
837                 free(b->machine);
838                 b->machine = machine;
839                 machine = NULL;
840         } else {
841                 b->machine = mfree(b->machine);
842         }
843
844         if (pid) {
845                 r = parse_pid(pid, &b->nspid);
846                 if (r < 0)
847                         return r;
848         } else
849                 b->nspid = 0;
850
851         b->sockaddr.un.sun_family = AF_UNIX;
852         strncpy(b->sockaddr.un.sun_path, "/var/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
853         b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + strlen("/var/run/dbus/system_bus_socket");
854
855         return 0;
856 }
857
858 static int parse_container_kernel_address(sd_bus *b, const char **p, char **guid) {
859         _cleanup_free_ char *machine = NULL, *pid = NULL;
860         int r;
861
862         assert(b);
863         assert(p);
864         assert(*p);
865         assert(guid);
866
867         while (**p != 0 && **p != ';') {
868                 r = parse_address_key(p, "guid", guid);
869                 if (r < 0)
870                         return r;
871                 else if (r > 0)
872                         continue;
873
874                 r = parse_address_key(p, "machine", &machine);
875                 if (r < 0)
876                         return r;
877                 else if (r > 0)
878                         continue;
879
880                 r = parse_address_key(p, "pid", &pid);
881                 if (r < 0)
882                         return r;
883                 else if (r > 0)
884                         continue;
885
886                 skip_address_key(p);
887         }
888
889         if (!machine == !pid)
890                 return -EINVAL;
891
892         if (machine) {
893                 if (!machine_name_is_valid(machine))
894                         return -EINVAL;
895
896                 free(b->machine);
897                 b->machine = machine;
898                 machine = NULL;
899         } else {
900                 b->machine = mfree(b->machine);
901         }
902
903         if (pid) {
904                 r = parse_pid(pid, &b->nspid);
905                 if (r < 0)
906                         return r;
907         } else
908                 b->nspid = 0;
909
910         r = free_and_strdup(&b->kernel, "/sys/fs/kdbus/0-system/bus");
911         if (r < 0)
912                 return r;
913
914         return 0;
915 }
916
917 static void bus_reset_parsed_address(sd_bus *b) {
918         assert(b);
919
920         zero(b->sockaddr);
921         b->sockaddr_size = 0;
922         b->exec_argv = strv_free(b->exec_argv);
923         b->exec_path = mfree(b->exec_path);
924         b->server_id = SD_ID128_NULL;
925         b->kernel = mfree(b->kernel);
926         b->machine = mfree(b->machine);
927         b->nspid = 0;
928 }
929
930 static int bus_parse_next_address(sd_bus *b) {
931         _cleanup_free_ char *guid = NULL;
932         const char *a;
933         int r;
934
935         assert(b);
936
937         if (!b->address)
938                 return 0;
939         if (b->address[b->address_index] == 0)
940                 return 0;
941
942         bus_reset_parsed_address(b);
943
944         a = b->address + b->address_index;
945
946         while (*a != 0) {
947
948                 if (*a == ';') {
949                         a++;
950                         continue;
951                 }
952
953                 if (startswith(a, "unix:")) {
954                         a += 5;
955
956                         r = parse_unix_address(b, &a, &guid);
957                         if (r < 0)
958                                 return r;
959                         break;
960
961                 } else if (startswith(a, "tcp:")) {
962
963                         a += 4;
964                         r = parse_tcp_address(b, &a, &guid);
965                         if (r < 0)
966                                 return r;
967
968                         break;
969
970                 } else if (startswith(a, "unixexec:")) {
971
972                         a += 9;
973                         r = parse_exec_address(b, &a, &guid);
974                         if (r < 0)
975                                 return r;
976
977                         break;
978
979                 } else if (startswith(a, "kernel:")) {
980
981                         a += 7;
982                         r = parse_kernel_address(b, &a, &guid);
983                         if (r < 0)
984                                 return r;
985
986                         break;
987                 } else if (startswith(a, "x-machine-unix:")) {
988
989                         a += 15;
990                         r = parse_container_unix_address(b, &a, &guid);
991                         if (r < 0)
992                                 return r;
993
994                         break;
995                 } else if (startswith(a, "x-machine-kernel:")) {
996
997                         a += 17;
998                         r = parse_container_kernel_address(b, &a, &guid);
999                         if (r < 0)
1000                                 return r;
1001
1002                         break;
1003                 }
1004
1005                 a = strchr(a, ';');
1006                 if (!a)
1007                         return 0;
1008         }
1009
1010         if (guid) {
1011                 r = sd_id128_from_string(guid, &b->server_id);
1012                 if (r < 0)
1013                         return r;
1014         }
1015
1016         b->address_index = a - b->address;
1017         return 1;
1018 }
1019
1020 static int bus_start_address(sd_bus *b) {
1021         bool container_kdbus_available = false;
1022         bool kdbus_available = false;
1023         int r;
1024
1025         assert(b);
1026
1027         for (;;) {
1028                 bool skipped = false;
1029
1030                 bus_close_fds(b);
1031
1032                 /*
1033                  * Usually, if you provide multiple different bus-addresses, we
1034                  * try all of them in order. We use the first one that
1035                  * succeeds. However, if you mix kernel and unix addresses, we
1036                  * never try unix-addresses if a previous kernel address was
1037                  * tried and kdbus was available. This is required to prevent
1038                  * clients to fallback to the bus-proxy if kdbus is available
1039                  * but failed (eg., too many connections).
1040                  */
1041
1042                 if (b->exec_path)
1043                         r = bus_socket_exec(b);
1044                 else if ((b->nspid > 0 || b->machine) && b->kernel) {
1045                         r = bus_container_connect_kernel(b);
1046                         if (r < 0 && !IN_SET(r, -ENOENT, -ESOCKTNOSUPPORT))
1047                                 container_kdbus_available = true;
1048
1049                 } else if ((b->nspid > 0 || b->machine) && b->sockaddr.sa.sa_family != AF_UNSPEC) {
1050                         if (!container_kdbus_available)
1051                                 r = bus_container_connect_socket(b);
1052                         else
1053                                 skipped = true;
1054
1055                 } else if (b->kernel) {
1056                         r = bus_kernel_connect(b);
1057                         if (r < 0 && !IN_SET(r, -ENOENT, -ESOCKTNOSUPPORT))
1058                                 kdbus_available = true;
1059
1060                 } else if (b->sockaddr.sa.sa_family != AF_UNSPEC) {
1061                         if (!kdbus_available)
1062                                 r = bus_socket_connect(b);
1063                         else
1064                                 skipped = true;
1065                 } else
1066                         skipped = true;
1067
1068                 if (!skipped) {
1069                         if (r >= 0) {
1070                                 r = attach_io_events(b);
1071                                 if (r >= 0)
1072                                         return r;
1073                         }
1074
1075                         b->last_connect_error = -r;
1076                 }
1077
1078                 r = bus_parse_next_address(b);
1079                 if (r < 0)
1080                         return r;
1081                 if (r == 0)
1082                         return b->last_connect_error ? -b->last_connect_error : -ECONNREFUSED;
1083         }
1084 }
1085
1086 int bus_next_address(sd_bus *b) {
1087         assert(b);
1088
1089         bus_reset_parsed_address(b);
1090         return bus_start_address(b);
1091 }
1092
1093 static int bus_start_fd(sd_bus *b) {
1094         struct stat st;
1095         int r;
1096
1097         assert(b);
1098         assert(b->input_fd >= 0);
1099         assert(b->output_fd >= 0);
1100
1101         r = fd_nonblock(b->input_fd, true);
1102         if (r < 0)
1103                 return r;
1104
1105         r = fd_cloexec(b->input_fd, true);
1106         if (r < 0)
1107                 return r;
1108
1109         if (b->input_fd != b->output_fd) {
1110                 r = fd_nonblock(b->output_fd, true);
1111                 if (r < 0)
1112                         return r;
1113
1114                 r = fd_cloexec(b->output_fd, true);
1115                 if (r < 0)
1116                         return r;
1117         }
1118
1119         if (fstat(b->input_fd, &st) < 0)
1120                 return -errno;
1121
1122         if (S_ISCHR(b->input_fd))
1123                 return bus_kernel_take_fd(b);
1124         else
1125                 return bus_socket_take_fd(b);
1126 }
1127
1128 _public_ int sd_bus_start(sd_bus *bus) {
1129         int r;
1130
1131         assert_return(bus, -EINVAL);
1132         assert_return(bus->state == BUS_UNSET, -EPERM);
1133         assert_return(!bus_pid_changed(bus), -ECHILD);
1134
1135         bus->state = BUS_OPENING;
1136
1137         if (bus->is_server && bus->bus_client)
1138                 return -EINVAL;
1139
1140         if (bus->input_fd >= 0)
1141                 r = bus_start_fd(bus);
1142         else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->kernel || bus->machine)
1143                 r = bus_start_address(bus);
1144         else
1145                 return -EINVAL;
1146
1147         if (r < 0) {
1148                 sd_bus_close(bus);
1149                 return r;
1150         }
1151
1152         return bus_send_hello(bus);
1153 }
1154
1155 _public_ int sd_bus_open(sd_bus **ret) {
1156         const char *e;
1157         sd_bus *b;
1158         int r;
1159
1160         assert_return(ret, -EINVAL);
1161
1162         /* Let's connect to the starter bus if it is set, and
1163          * otherwise to the bus that is appropropriate for the scope
1164          * we are running in */
1165
1166         e = secure_getenv("DBUS_STARTER_BUS_TYPE");
1167         if (e) {
1168                 if (streq(e, "system"))
1169                         return sd_bus_open_system(ret);
1170 /// elogind does not support systemd units
1171 #if 0
1172                 else if (STR_IN_SET(e, "session", "user"))
1173                         return sd_bus_open_user(ret);
1174 #endif // 0
1175         }
1176
1177         e = secure_getenv("DBUS_STARTER_ADDRESS");
1178         if (!e) {
1179 /// elogind does not support systemd units
1180 #if 0
1181                 if (cg_pid_get_owner_uid(0, NULL) >= 0)
1182                         return sd_bus_open_user(ret);
1183                 else
1184 #endif // 0
1185                 return sd_bus_open_system(ret);
1186         }
1187
1188         r = sd_bus_new(&b);
1189         if (r < 0)
1190                 return r;
1191
1192         r = sd_bus_set_address(b, e);
1193         if (r < 0)
1194                 goto fail;
1195
1196         b->bus_client = true;
1197
1198         /* We don't know whether the bus is trusted or not, so better
1199          * be safe, and authenticate everything */
1200         b->trusted = false;
1201         b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1202         b->creds_mask |= SD_BUS_CREDS_UID | SD_BUS_CREDS_EUID | SD_BUS_CREDS_EFFECTIVE_CAPS;
1203
1204         r = sd_bus_start(b);
1205         if (r < 0)
1206                 goto fail;
1207
1208         *ret = b;
1209         return 0;
1210
1211 fail:
1212         bus_free(b);
1213         return r;
1214 }
1215
1216 int bus_set_address_system(sd_bus *b) {
1217         const char *e;
1218         assert(b);
1219
1220         e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1221         if (e)
1222                 return sd_bus_set_address(b, e);
1223
1224         return sd_bus_set_address(b, DEFAULT_SYSTEM_BUS_ADDRESS);
1225 }
1226
1227 _public_ int sd_bus_open_system(sd_bus **ret) {
1228         sd_bus *b;
1229         int r;
1230
1231         assert_return(ret, -EINVAL);
1232
1233         r = sd_bus_new(&b);
1234         if (r < 0)
1235                 return r;
1236
1237         r = bus_set_address_system(b);
1238         if (r < 0)
1239                 goto fail;
1240
1241         b->bus_client = true;
1242         b->is_system = true;
1243
1244         /* Let's do per-method access control on the system bus. We
1245          * need the caller's UID and capability set for that. */
1246         b->trusted = false;
1247         b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1248         b->creds_mask |= SD_BUS_CREDS_UID | SD_BUS_CREDS_EUID | SD_BUS_CREDS_EFFECTIVE_CAPS;
1249
1250         r = sd_bus_start(b);
1251         if (r < 0)
1252                 goto fail;
1253
1254         *ret = b;
1255         return 0;
1256
1257 fail:
1258         bus_free(b);
1259         return r;
1260 }
1261
1262 /// elogind can not open/use a user bus
1263 #if 0
1264 int bus_set_address_user(sd_bus *b) {
1265         const char *e;
1266         uid_t uid;
1267         int r;
1268
1269         assert(b);
1270
1271         e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
1272         if (e)
1273                 return sd_bus_set_address(b, e);
1274
1275         r = cg_pid_get_owner_uid(0, &uid);
1276         if (r < 0)
1277                 uid = getuid();
1278
1279         e = secure_getenv("XDG_RUNTIME_DIR");
1280         if (e) {
1281                 _cleanup_free_ char *ee = NULL;
1282
1283                 ee = bus_address_escape(e);
1284                 if (!ee)
1285                         return -ENOMEM;
1286
1287                 (void) asprintf(&b->address, KERNEL_USER_BUS_ADDRESS_FMT ";" UNIX_USER_BUS_ADDRESS_FMT, uid, ee);
1288         } else
1289                 (void) asprintf(&b->address, KERNEL_USER_BUS_ADDRESS_FMT, uid);
1290
1291         if (!b->address)
1292                 return -ENOMEM;
1293
1294         return 0;
1295 }
1296 #endif // 0
1297
1298 _public_ int sd_bus_open_user(sd_bus **ret) {
1299 /// elogind does not support user buses
1300 #if 0
1301         sd_bus *b;
1302         int r;
1303
1304         assert_return(ret, -EINVAL);
1305
1306         r = sd_bus_new(&b);
1307         if (r < 0)
1308                 return r;
1309
1310         r = bus_set_address_user(b);
1311         if (r < 0)
1312                 return r;
1313
1314         b->bus_client = true;
1315         b->is_user = true;
1316
1317         /* We don't do any per-method access control on the user
1318          * bus. */
1319         b->trusted = true;
1320
1321         r = sd_bus_start(b);
1322         if (r < 0)
1323                 goto fail;
1324
1325         *ret = b;
1326         return 0;
1327
1328 fail:
1329         bus_free(b);
1330         return r;
1331 #else
1332         return sd_bus_open_system(ret);
1333 #endif // 0
1334 }
1335
1336 int bus_set_address_system_remote(sd_bus *b, const char *host) {
1337         _cleanup_free_ char *e = NULL;
1338         char *m = NULL, *c = NULL;
1339
1340         assert(b);
1341         assert(host);
1342
1343         /* Let's see if we shall enter some container */
1344         m = strchr(host, ':');
1345         if (m) {
1346                 m++;
1347
1348                 /* Let's make sure this is not a port of some kind,
1349                  * and is a valid machine name. */
1350                 if (!in_charset(m, "0123456789") && machine_name_is_valid(m)) {
1351                         char *t;
1352
1353                         /* Cut out the host part */
1354                         t = strndupa(host, m - host - 1);
1355                         e = bus_address_escape(t);
1356                         if (!e)
1357                                 return -ENOMEM;
1358
1359                         c = strjoina(",argv4=--machine=", m);
1360                 }
1361         }
1362
1363         if (!e) {
1364                 e = bus_address_escape(host);
1365                 if (!e)
1366                         return -ENOMEM;
1367         }
1368
1369         b->address = strjoin("unixexec:path=ssh,argv1=-xT,argv2=", e, ",argv3=systemd-stdio-bridge", c, NULL);
1370         if (!b->address)
1371                 return -ENOMEM;
1372
1373         return 0;
1374  }
1375
1376 _public_ int sd_bus_open_system_remote(sd_bus **ret, const char *host) {
1377         sd_bus *bus;
1378         int r;
1379
1380         assert_return(host, -EINVAL);
1381         assert_return(ret, -EINVAL);
1382
1383         r = sd_bus_new(&bus);
1384         if (r < 0)
1385                 return r;
1386
1387         r = bus_set_address_system_remote(bus, host);
1388         if (r < 0)
1389                 goto fail;
1390
1391         bus->bus_client = true;
1392         bus->trusted = false;
1393         bus->is_system = true;
1394
1395         r = sd_bus_start(bus);
1396         if (r < 0)
1397                 goto fail;
1398
1399         *ret = bus;
1400         return 0;
1401
1402 fail:
1403         bus_free(bus);
1404         return r;
1405 }
1406
1407 int bus_set_address_system_machine(sd_bus *b, const char *machine) {
1408         _cleanup_free_ char *e = NULL;
1409
1410         assert(b);
1411         assert(machine);
1412
1413         e = bus_address_escape(machine);
1414         if (!e)
1415                 return -ENOMEM;
1416
1417         b->address = strjoin("x-machine-kernel:machine=", e, ";x-machine-unix:machine=", e, NULL);
1418         if (!b->address)
1419                 return -ENOMEM;
1420
1421         return 0;
1422 }
1423
1424 _public_ int sd_bus_open_system_machine(sd_bus **ret, const char *machine) {
1425         sd_bus *bus;
1426         int r;
1427
1428         assert_return(machine, -EINVAL);
1429         assert_return(ret, -EINVAL);
1430         assert_return(machine_name_is_valid(machine), -EINVAL);
1431
1432         r = sd_bus_new(&bus);
1433         if (r < 0)
1434                 return r;
1435
1436         r = bus_set_address_system_machine(bus, machine);
1437         if (r < 0)
1438                 goto fail;
1439
1440         bus->bus_client = true;
1441         bus->trusted = false;
1442         bus->is_system = true;
1443
1444         r = sd_bus_start(bus);
1445         if (r < 0)
1446                 goto fail;
1447
1448         *ret = bus;
1449         return 0;
1450
1451 fail:
1452         bus_free(bus);
1453         return r;
1454 }
1455
1456 _public_ void sd_bus_close(sd_bus *bus) {
1457
1458         if (!bus)
1459                 return;
1460         if (bus->state == BUS_CLOSED)
1461                 return;
1462         if (bus_pid_changed(bus))
1463                 return;
1464
1465         bus->state = BUS_CLOSED;
1466
1467         sd_bus_detach_event(bus);
1468
1469         /* Drop all queued messages so that they drop references to
1470          * the bus object and the bus may be freed */
1471         bus_reset_queues(bus);
1472
1473         if (!bus->is_kernel)
1474                 bus_close_fds(bus);
1475
1476         /* We'll leave the fd open in case this is a kernel bus, since
1477          * there might still be memblocks around that reference this
1478          * bus, and they might need to invoke the KDBUS_CMD_FREE
1479          * ioctl on the fd when they are freed. */
1480 }
1481
1482 _public_ sd_bus* sd_bus_flush_close_unref(sd_bus *bus) {
1483
1484         if (!bus)
1485                 return NULL;
1486
1487         sd_bus_flush(bus);
1488         sd_bus_close(bus);
1489
1490         return sd_bus_unref(bus);
1491 }
1492
1493 static void bus_enter_closing(sd_bus *bus) {
1494         assert(bus);
1495
1496         if (bus->state != BUS_OPENING &&
1497             bus->state != BUS_AUTHENTICATING &&
1498             bus->state != BUS_HELLO &&
1499             bus->state != BUS_RUNNING)
1500                 return;
1501
1502         bus->state = BUS_CLOSING;
1503 }
1504
1505 _public_ sd_bus *sd_bus_ref(sd_bus *bus) {
1506         assert_return(bus, NULL);
1507
1508         assert_se(REFCNT_INC(bus->n_ref) >= 2);
1509
1510         return bus;
1511 }
1512
1513 _public_ sd_bus *sd_bus_unref(sd_bus *bus) {
1514         unsigned i;
1515
1516         if (!bus)
1517                 return NULL;
1518
1519         i = REFCNT_DEC(bus->n_ref);
1520         if (i > 0)
1521                 return NULL;
1522
1523         bus_free(bus);
1524         return NULL;
1525 }
1526
1527 /// UNNEEDED by elogind
1528 #if 0
1529 _public_ int sd_bus_is_open(sd_bus *bus) {
1530
1531         assert_return(bus, -EINVAL);
1532         assert_return(!bus_pid_changed(bus), -ECHILD);
1533
1534         return BUS_IS_OPEN(bus->state);
1535 }
1536 #endif // 0
1537
1538 _public_ int sd_bus_can_send(sd_bus *bus, char type) {
1539         int r;
1540
1541         assert_return(bus, -EINVAL);
1542         assert_return(bus->state != BUS_UNSET, -ENOTCONN);
1543         assert_return(!bus_pid_changed(bus), -ECHILD);
1544
1545         if (bus->hello_flags & KDBUS_HELLO_MONITOR)
1546                 return 0;
1547
1548         if (type == SD_BUS_TYPE_UNIX_FD) {
1549                 if (!(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD))
1550                         return 0;
1551
1552                 r = bus_ensure_running(bus);
1553                 if (r < 0)
1554                         return r;
1555
1556                 return bus->can_fds;
1557         }
1558
1559         return bus_type_is_valid(type);
1560 }
1561
1562 /// UNNEEDED by elogind
1563 #if 0
1564 _public_ int sd_bus_get_bus_id(sd_bus *bus, sd_id128_t *id) {
1565         int r;
1566
1567         assert_return(bus, -EINVAL);
1568         assert_return(id, -EINVAL);
1569         assert_return(!bus_pid_changed(bus), -ECHILD);
1570
1571         r = bus_ensure_running(bus);
1572         if (r < 0)
1573                 return r;
1574
1575         *id = bus->server_id;
1576         return 0;
1577 }
1578 #endif // 0
1579
1580 static int bus_seal_message(sd_bus *b, sd_bus_message *m, usec_t timeout) {
1581         assert(b);
1582         assert(m);
1583
1584         if (m->sealed) {
1585                 /* If we copy the same message to multiple
1586                  * destinations, avoid using the same cookie
1587                  * numbers. */
1588                 b->cookie = MAX(b->cookie, BUS_MESSAGE_COOKIE(m));
1589                 return 0;
1590         }
1591
1592         if (timeout == 0)
1593                 timeout = BUS_DEFAULT_TIMEOUT;
1594
1595         return bus_message_seal(m, ++b->cookie, timeout);
1596 }
1597
1598 static int bus_remarshal_message(sd_bus *b, sd_bus_message **m) {
1599         bool remarshal = false;
1600
1601         assert(b);
1602
1603         /* wrong packet version */
1604         if (b->message_version != 0 && b->message_version != (*m)->header->version)
1605                 remarshal = true;
1606
1607         /* wrong packet endianness */
1608         if (b->message_endian != 0 && b->message_endian != (*m)->header->endian)
1609                 remarshal = true;
1610
1611         /* TODO: kdbus-messages received from the kernel contain data which is
1612          * not allowed to be passed to KDBUS_CMD_SEND. Therefore, we have to
1613          * force remarshaling of the message. Technically, we could just
1614          * recreate the kdbus message, but that is non-trivial as other parts of
1615          * the message refer to m->kdbus already. This should be fixed! */
1616         if ((*m)->kdbus && (*m)->release_kdbus)
1617                 remarshal = true;
1618
1619         return remarshal ? bus_message_remarshal(b, m) : 0;
1620 }
1621
1622 int bus_seal_synthetic_message(sd_bus *b, sd_bus_message *m) {
1623         assert(b);
1624         assert(m);
1625
1626         /* Fake some timestamps, if they were requested, and not
1627          * already initialized */
1628         if (b->attach_flags & KDBUS_ATTACH_TIMESTAMP) {
1629                 if (m->realtime <= 0)
1630                         m->realtime = now(CLOCK_REALTIME);
1631
1632                 if (m->monotonic <= 0)
1633                         m->monotonic = now(CLOCK_MONOTONIC);
1634         }
1635
1636         /* The bus specification says the serial number cannot be 0,
1637          * hence let's fill something in for synthetic messages. Since
1638          * synthetic messages might have a fake sender and we don't
1639          * want to interfere with the real sender's serial numbers we
1640          * pick a fixed, artificial one. We use (uint32_t) -1 rather
1641          * than (uint64_t) -1 since dbus1 only had 32bit identifiers,
1642          * even though kdbus can do 64bit. */
1643         return bus_message_seal(m, 0xFFFFFFFFULL, 0);
1644 }
1645
1646 static int bus_write_message(sd_bus *bus, sd_bus_message *m, bool hint_sync_call, size_t *idx) {
1647         int r;
1648
1649         assert(bus);
1650         assert(m);
1651
1652         if (bus->is_kernel)
1653                 r = bus_kernel_write_message(bus, m, hint_sync_call);
1654         else
1655                 r = bus_socket_write_message(bus, m, idx);
1656
1657         if (r <= 0)
1658                 return r;
1659
1660         if (bus->is_kernel || *idx >= BUS_MESSAGE_SIZE(m))
1661                 log_debug("Sent message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%" PRIu64 " reply_cookie=%" PRIu64 " error=%s",
1662                           bus_message_type_to_string(m->header->type),
1663                           strna(sd_bus_message_get_sender(m)),
1664                           strna(sd_bus_message_get_destination(m)),
1665                           strna(sd_bus_message_get_path(m)),
1666                           strna(sd_bus_message_get_interface(m)),
1667                           strna(sd_bus_message_get_member(m)),
1668                           BUS_MESSAGE_COOKIE(m),
1669                           m->reply_cookie,
1670                           strna(m->error.message));
1671
1672         return r;
1673 }
1674
1675 static int dispatch_wqueue(sd_bus *bus) {
1676         int r, ret = 0;
1677
1678         assert(bus);
1679         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1680
1681         while (bus->wqueue_size > 0) {
1682
1683                 r = bus_write_message(bus, bus->wqueue[0], false, &bus->windex);
1684                 if (r < 0)
1685                         return r;
1686                 else if (r == 0)
1687                         /* Didn't do anything this time */
1688                         return ret;
1689                 else if (bus->is_kernel || bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
1690                         /* Fully written. Let's drop the entry from
1691                          * the queue.
1692                          *
1693                          * This isn't particularly optimized, but
1694                          * well, this is supposed to be our worst-case
1695                          * buffer only, and the socket buffer is
1696                          * supposed to be our primary buffer, and if
1697                          * it got full, then all bets are off
1698                          * anyway. */
1699
1700                         bus->wqueue_size --;
1701                         sd_bus_message_unref(bus->wqueue[0]);
1702                         memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
1703                         bus->windex = 0;
1704
1705                         ret = 1;
1706                 }
1707         }
1708
1709         return ret;
1710 }
1711
1712 static int bus_read_message(sd_bus *bus, bool hint_priority, int64_t priority) {
1713         assert(bus);
1714
1715         if (bus->is_kernel)
1716                 return bus_kernel_read_message(bus, hint_priority, priority);
1717         else
1718                 return bus_socket_read_message(bus);
1719 }
1720
1721 int bus_rqueue_make_room(sd_bus *bus) {
1722         assert(bus);
1723
1724         if (bus->rqueue_size >= BUS_RQUEUE_MAX)
1725                 return -ENOBUFS;
1726
1727         if (!GREEDY_REALLOC(bus->rqueue, bus->rqueue_allocated, bus->rqueue_size + 1))
1728                 return -ENOMEM;
1729
1730         return 0;
1731 }
1732
1733 static int dispatch_rqueue(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **m) {
1734         int r, ret = 0;
1735
1736         assert(bus);
1737         assert(m);
1738         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1739
1740         /* Note that the priority logic is only available on kdbus,
1741          * where the rqueue is unused. We check the rqueue here
1742          * anyway, because it's simple... */
1743
1744         for (;;) {
1745                 if (bus->rqueue_size > 0) {
1746                         /* Dispatch a queued message */
1747
1748                         *m = bus->rqueue[0];
1749                         bus->rqueue_size --;
1750                         memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
1751                         return 1;
1752                 }
1753
1754                 /* Try to read a new message */
1755                 r = bus_read_message(bus, hint_priority, priority);
1756                 if (r < 0)
1757                         return r;
1758                 if (r == 0)
1759                         return ret;
1760
1761                 ret = 1;
1762         }
1763 }
1764
1765 static int bus_send_internal(sd_bus *bus, sd_bus_message *_m, uint64_t *cookie, bool hint_sync_call) {
1766         _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1767         int r;
1768
1769         assert_return(m, -EINVAL);
1770
1771         if (!bus)
1772                 bus = m->bus;
1773
1774         assert_return(!bus_pid_changed(bus), -ECHILD);
1775         assert_return(!bus->is_kernel || !(bus->hello_flags & KDBUS_HELLO_MONITOR), -EROFS);
1776
1777         if (!BUS_IS_OPEN(bus->state))
1778                 return -ENOTCONN;
1779
1780         if (m->n_fds > 0) {
1781                 r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
1782                 if (r < 0)
1783                         return r;
1784                 if (r == 0)
1785                         return -EOPNOTSUPP;
1786         }
1787
1788         /* If the cookie number isn't kept, then we know that no reply
1789          * is expected */
1790         if (!cookie && !m->sealed)
1791                 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1792
1793         r = bus_seal_message(bus, m, 0);
1794         if (r < 0)
1795                 return r;
1796
1797         /* Remarshall if we have to. This will possibly unref the
1798          * message and place a replacement in m */
1799         r = bus_remarshal_message(bus, &m);
1800         if (r < 0)
1801                 return r;
1802
1803         /* If this is a reply and no reply was requested, then let's
1804          * suppress this, if we can */
1805         if (m->dont_send)
1806                 goto finish;
1807
1808         if ((bus->state == BUS_RUNNING || bus->state == BUS_HELLO) && bus->wqueue_size <= 0) {
1809                 size_t idx = 0;
1810
1811                 r = bus_write_message(bus, m, hint_sync_call, &idx);
1812                 if (r < 0) {
1813                         if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
1814                                 bus_enter_closing(bus);
1815                                 return -ECONNRESET;
1816                         }
1817
1818                         return r;
1819                 }
1820
1821                 if (!bus->is_kernel && idx < BUS_MESSAGE_SIZE(m))  {
1822                         /* Wasn't fully written. So let's remember how
1823                          * much was written. Note that the first entry
1824                          * of the wqueue array is always allocated so
1825                          * that we always can remember how much was
1826                          * written. */
1827                         bus->wqueue[0] = sd_bus_message_ref(m);
1828                         bus->wqueue_size = 1;
1829                         bus->windex = idx;
1830                 }
1831
1832         } else {
1833                 /* Just append it to the queue. */
1834
1835                 if (bus->wqueue_size >= BUS_WQUEUE_MAX)
1836                         return -ENOBUFS;
1837
1838                 if (!GREEDY_REALLOC(bus->wqueue, bus->wqueue_allocated, bus->wqueue_size + 1))
1839                         return -ENOMEM;
1840
1841                 bus->wqueue[bus->wqueue_size ++] = sd_bus_message_ref(m);
1842         }
1843
1844 finish:
1845         if (cookie)
1846                 *cookie = BUS_MESSAGE_COOKIE(m);
1847
1848         return 1;
1849 }
1850
1851 _public_ int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *cookie) {
1852         return bus_send_internal(bus, m, cookie, false);
1853 }
1854
1855 /// UNNEEDED by elogind
1856 #if 0
1857 _public_ int sd_bus_send_to(sd_bus *bus, sd_bus_message *m, const char *destination, uint64_t *cookie) {
1858         int r;
1859
1860         assert_return(m, -EINVAL);
1861
1862         if (!bus)
1863                 bus = m->bus;
1864
1865         assert_return(!bus_pid_changed(bus), -ECHILD);
1866
1867         if (!BUS_IS_OPEN(bus->state))
1868                 return -ENOTCONN;
1869
1870         if (!streq_ptr(m->destination, destination)) {
1871
1872                 if (!destination)
1873                         return -EEXIST;
1874
1875                 r = sd_bus_message_set_destination(m, destination);
1876                 if (r < 0)
1877                         return r;
1878         }
1879
1880         return sd_bus_send(bus, m, cookie);
1881 }
1882 #endif // 0
1883
1884 static usec_t calc_elapse(uint64_t usec) {
1885         if (usec == (uint64_t) -1)
1886                 return 0;
1887
1888         return now(CLOCK_MONOTONIC) + usec;
1889 }
1890
1891 static int timeout_compare(const void *a, const void *b) {
1892         const struct reply_callback *x = a, *y = b;
1893
1894         if (x->timeout != 0 && y->timeout == 0)
1895                 return -1;
1896
1897         if (x->timeout == 0 && y->timeout != 0)
1898                 return 1;
1899
1900         if (x->timeout < y->timeout)
1901                 return -1;
1902
1903         if (x->timeout > y->timeout)
1904                 return 1;
1905
1906         return 0;
1907 }
1908
1909 _public_ int sd_bus_call_async(
1910                 sd_bus *bus,
1911                 sd_bus_slot **slot,
1912                 sd_bus_message *_m,
1913                 sd_bus_message_handler_t callback,
1914                 void *userdata,
1915                 uint64_t usec) {
1916
1917         _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
1918         _cleanup_bus_slot_unref_ sd_bus_slot *s = NULL;
1919         int r;
1920
1921         assert_return(m, -EINVAL);
1922         assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1923         assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1924         assert_return(callback, -EINVAL);
1925
1926         if (!bus)
1927                 bus = m->bus;
1928
1929         assert_return(!bus_pid_changed(bus), -ECHILD);
1930         assert_return(!bus->is_kernel || !(bus->hello_flags & KDBUS_HELLO_MONITOR), -EROFS);
1931
1932         if (!BUS_IS_OPEN(bus->state))
1933                 return -ENOTCONN;
1934
1935         r = ordered_hashmap_ensure_allocated(&bus->reply_callbacks, &uint64_hash_ops);
1936         if (r < 0)
1937                 return r;
1938
1939         r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
1940         if (r < 0)
1941                 return r;
1942
1943         r = bus_seal_message(bus, m, usec);
1944         if (r < 0)
1945                 return r;
1946
1947         r = bus_remarshal_message(bus, &m);
1948         if (r < 0)
1949                 return r;
1950
1951         s = bus_slot_allocate(bus, !slot, BUS_REPLY_CALLBACK, sizeof(struct reply_callback), userdata);
1952         if (!s)
1953                 return -ENOMEM;
1954
1955         s->reply_callback.callback = callback;
1956
1957         s->reply_callback.cookie = BUS_MESSAGE_COOKIE(m);
1958         r = ordered_hashmap_put(bus->reply_callbacks, &s->reply_callback.cookie, &s->reply_callback);
1959         if (r < 0) {
1960                 s->reply_callback.cookie = 0;
1961                 return r;
1962         }
1963
1964         s->reply_callback.timeout = calc_elapse(m->timeout);
1965         if (s->reply_callback.timeout != 0) {
1966                 r = prioq_put(bus->reply_callbacks_prioq, &s->reply_callback, &s->reply_callback.prioq_idx);
1967                 if (r < 0) {
1968                         s->reply_callback.timeout = 0;
1969                         return r;
1970                 }
1971         }
1972
1973         r = sd_bus_send(bus, m, &s->reply_callback.cookie);
1974         if (r < 0)
1975                 return r;
1976
1977         if (slot)
1978                 *slot = s;
1979         s = NULL;
1980
1981         return r;
1982 }
1983
1984 int bus_ensure_running(sd_bus *bus) {
1985         int r;
1986
1987         assert(bus);
1988
1989         if (bus->state == BUS_UNSET || bus->state == BUS_CLOSED || bus->state == BUS_CLOSING)
1990                 return -ENOTCONN;
1991         if (bus->state == BUS_RUNNING)
1992                 return 1;
1993
1994         for (;;) {
1995                 r = sd_bus_process(bus, NULL);
1996                 if (r < 0)
1997                         return r;
1998                 if (bus->state == BUS_RUNNING)
1999                         return 1;
2000                 if (r > 0)
2001                         continue;
2002
2003                 r = sd_bus_wait(bus, (uint64_t) -1);
2004                 if (r < 0)
2005                         return r;
2006         }
2007 }
2008
2009 _public_ int sd_bus_call(
2010                 sd_bus *bus,
2011                 sd_bus_message *_m,
2012                 uint64_t usec,
2013                 sd_bus_error *error,
2014                 sd_bus_message **reply) {
2015
2016         _cleanup_bus_message_unref_ sd_bus_message *m = sd_bus_message_ref(_m);
2017         usec_t timeout;
2018         uint64_t cookie;
2019         unsigned i;
2020         int r;
2021
2022         bus_assert_return(m, -EINVAL, error);
2023         bus_assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL, error);
2024         bus_assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL, error);
2025         bus_assert_return(!bus_error_is_dirty(error), -EINVAL, error);
2026
2027         if (!bus)
2028                 bus = m->bus;
2029
2030         bus_assert_return(!bus_pid_changed(bus), -ECHILD, error);
2031         bus_assert_return(!bus->is_kernel || !(bus->hello_flags & KDBUS_HELLO_MONITOR), -EROFS, error);
2032
2033         if (!BUS_IS_OPEN(bus->state)) {
2034                 r = -ENOTCONN;
2035                 goto fail;
2036         }
2037
2038         r = bus_ensure_running(bus);
2039         if (r < 0)
2040                 goto fail;
2041
2042         i = bus->rqueue_size;
2043
2044         r = bus_seal_message(bus, m, usec);
2045         if (r < 0)
2046                 goto fail;
2047
2048         r = bus_remarshal_message(bus, &m);
2049         if (r < 0)
2050                 goto fail;
2051
2052         r = bus_send_internal(bus, m, &cookie, true);
2053         if (r < 0)
2054                 goto fail;
2055
2056         timeout = calc_elapse(m->timeout);
2057
2058         for (;;) {
2059                 usec_t left;
2060
2061                 while (i < bus->rqueue_size) {
2062                         sd_bus_message *incoming = NULL;
2063
2064                         incoming = bus->rqueue[i];
2065
2066                         if (incoming->reply_cookie == cookie) {
2067                                 /* Found a match! */
2068
2069                                 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
2070                                 bus->rqueue_size--;
2071                                 log_debug_bus_message(incoming);
2072
2073                                 if (incoming->header->type == SD_BUS_MESSAGE_METHOD_RETURN) {
2074
2075                                         if (incoming->n_fds <= 0 || (bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)) {
2076                                                 if (reply)
2077                                                         *reply = incoming;
2078                                                 else
2079                                                         sd_bus_message_unref(incoming);
2080
2081                                                 return 1;
2082                                         }
2083
2084                                         r = sd_bus_error_setf(error, SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Reply message contained file descriptors which I couldn't accept. Sorry.");
2085                                         sd_bus_message_unref(incoming);
2086                                         return r;
2087
2088                                 } else if (incoming->header->type == SD_BUS_MESSAGE_METHOD_ERROR) {
2089                                         r = sd_bus_error_copy(error, &incoming->error);
2090                                 sd_bus_message_unref(incoming);
2091                                 return r;
2092                                 } else {
2093                                         r = -EIO;
2094                                         goto fail;
2095                                 }
2096
2097                         } else if (BUS_MESSAGE_COOKIE(incoming) == cookie &&
2098                                    bus->unique_name &&
2099                                    incoming->sender &&
2100                                    streq(bus->unique_name, incoming->sender)) {
2101
2102                                 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
2103                                 bus->rqueue_size--;
2104
2105                                 /* Our own message? Somebody is trying
2106                                  * to send its own client a message,
2107                                  * let's not dead-lock, let's fail
2108                                  * immediately. */
2109
2110                                 sd_bus_message_unref(incoming);
2111                                 r = -ELOOP;
2112                                 goto fail;
2113                         }
2114
2115                         /* Try to read more, right-away */
2116                         i++;
2117                 }
2118
2119                 r = bus_read_message(bus, false, 0);
2120                 if (r < 0) {
2121                         if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2122                                 bus_enter_closing(bus);
2123                                 r = -ECONNRESET;
2124                         }
2125
2126                         goto fail;
2127                 }
2128                 if (r > 0)
2129                         continue;
2130
2131                 if (timeout > 0) {
2132                         usec_t n;
2133
2134                         n = now(CLOCK_MONOTONIC);
2135                         if (n >= timeout) {
2136                                 r = -ETIMEDOUT;
2137                                 goto fail;
2138                         }
2139
2140                         left = timeout - n;
2141                 } else
2142                         left = (uint64_t) -1;
2143
2144                 r = bus_poll(bus, true, left);
2145                 if (r < 0)
2146                         goto fail;
2147                 if (r == 0) {
2148                         r = -ETIMEDOUT;
2149                         goto fail;
2150                 }
2151
2152                 r = dispatch_wqueue(bus);
2153                 if (r < 0) {
2154                         if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2155                                 bus_enter_closing(bus);
2156                                 r = -ECONNRESET;
2157                         }
2158
2159                         goto fail;
2160                 }
2161         }
2162
2163 fail:
2164         return sd_bus_error_set_errno(error, r);
2165 }
2166
2167 /// UNNEEDED by elogind
2168 #if 0
2169 _public_ int sd_bus_get_fd(sd_bus *bus) {
2170
2171         assert_return(bus, -EINVAL);
2172         assert_return(bus->input_fd == bus->output_fd, -EPERM);
2173         assert_return(!bus_pid_changed(bus), -ECHILD);
2174
2175         return bus->input_fd;
2176 }
2177 #endif // 0
2178
2179 _public_ int sd_bus_get_events(sd_bus *bus) {
2180         int flags = 0;
2181
2182         assert_return(bus, -EINVAL);
2183         assert_return(!bus_pid_changed(bus), -ECHILD);
2184
2185         if (!BUS_IS_OPEN(bus->state) && bus->state != BUS_CLOSING)
2186                 return -ENOTCONN;
2187
2188         if (bus->state == BUS_OPENING)
2189                 flags |= POLLOUT;
2190         else if (bus->state == BUS_AUTHENTICATING) {
2191
2192                 if (bus_socket_auth_needs_write(bus))
2193                         flags |= POLLOUT;
2194
2195                 flags |= POLLIN;
2196
2197         } else if (bus->state == BUS_RUNNING || bus->state == BUS_HELLO) {
2198                 if (bus->rqueue_size <= 0)
2199                         flags |= POLLIN;
2200                 if (bus->wqueue_size > 0)
2201                         flags |= POLLOUT;
2202         }
2203
2204         return flags;
2205 }
2206
2207 _public_ int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
2208         struct reply_callback *c;
2209
2210         assert_return(bus, -EINVAL);
2211         assert_return(timeout_usec, -EINVAL);
2212         assert_return(!bus_pid_changed(bus), -ECHILD);
2213
2214         if (!BUS_IS_OPEN(bus->state) && bus->state != BUS_CLOSING)
2215                 return -ENOTCONN;
2216
2217         if (bus->track_queue) {
2218                 *timeout_usec = 0;
2219                 return 1;
2220         }
2221
2222         if (bus->state == BUS_CLOSING) {
2223                 *timeout_usec = 0;
2224                 return 1;
2225         }
2226
2227         if (bus->state == BUS_AUTHENTICATING) {
2228                 *timeout_usec = bus->auth_timeout;
2229                 return 1;
2230         }
2231
2232         if (bus->state != BUS_RUNNING && bus->state != BUS_HELLO) {
2233                 *timeout_usec = (uint64_t) -1;
2234                 return 0;
2235         }
2236
2237         if (bus->rqueue_size > 0) {
2238                 *timeout_usec = 0;
2239                 return 1;
2240         }
2241
2242         c = prioq_peek(bus->reply_callbacks_prioq);
2243         if (!c) {
2244                 *timeout_usec = (uint64_t) -1;
2245                 return 0;
2246         }
2247
2248         if (c->timeout == 0) {
2249                 *timeout_usec = (uint64_t) -1;
2250                 return 0;
2251         }
2252
2253         *timeout_usec = c->timeout;
2254         return 1;
2255 }
2256
2257 static int process_timeout(sd_bus *bus) {
2258         _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2259         _cleanup_bus_message_unref_ sd_bus_message* m = NULL;
2260         struct reply_callback *c;
2261         sd_bus_slot *slot;
2262         usec_t n;
2263         int r;
2264
2265         assert(bus);
2266
2267         c = prioq_peek(bus->reply_callbacks_prioq);
2268         if (!c)
2269                 return 0;
2270
2271         n = now(CLOCK_MONOTONIC);
2272         if (c->timeout > n)
2273                 return 0;
2274
2275         r = bus_message_new_synthetic_error(
2276                         bus,
2277                         c->cookie,
2278                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
2279                         &m);
2280         if (r < 0)
2281                 return r;
2282
2283         r = bus_seal_synthetic_message(bus, m);
2284         if (r < 0)
2285                 return r;
2286
2287         assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
2288         c->timeout = 0;
2289
2290         ordered_hashmap_remove(bus->reply_callbacks, &c->cookie);
2291         c->cookie = 0;
2292
2293         slot = container_of(c, sd_bus_slot, reply_callback);
2294
2295         bus->iteration_counter ++;
2296
2297         bus->current_message = m;
2298         bus->current_slot = sd_bus_slot_ref(slot);
2299         bus->current_handler = c->callback;
2300         bus->current_userdata = slot->userdata;
2301         r = c->callback(m, slot->userdata, &error_buffer);
2302         bus->current_userdata = NULL;
2303         bus->current_handler = NULL;
2304         bus->current_slot = NULL;
2305         bus->current_message = NULL;
2306
2307         if (slot->floating) {
2308                 bus_slot_disconnect(slot);
2309                 sd_bus_slot_unref(slot);
2310         }
2311
2312         sd_bus_slot_unref(slot);
2313
2314         return bus_maybe_reply_error(m, r, &error_buffer);
2315 }
2316
2317 static int process_hello(sd_bus *bus, sd_bus_message *m) {
2318         assert(bus);
2319         assert(m);
2320
2321         if (bus->state != BUS_HELLO)
2322                 return 0;
2323
2324         /* Let's make sure the first message on the bus is the HELLO
2325          * reply. But note that we don't actually parse the message
2326          * here (we leave that to the usual handling), we just verify
2327          * we don't let any earlier msg through. */
2328
2329         if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2330             m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2331                 return -EIO;
2332
2333         if (m->reply_cookie != 1)
2334                 return -EIO;
2335
2336         return 0;
2337 }
2338
2339 static int process_reply(sd_bus *bus, sd_bus_message *m) {
2340         _cleanup_bus_message_unref_ sd_bus_message *synthetic_reply = NULL;
2341         _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2342         struct reply_callback *c;
2343         sd_bus_slot *slot;
2344         int r;
2345
2346         assert(bus);
2347         assert(m);
2348
2349         if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2350             m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2351                 return 0;
2352
2353         if (bus->is_kernel && (bus->hello_flags & KDBUS_HELLO_MONITOR))
2354                 return 0;
2355
2356         if (m->destination && bus->unique_name && !streq_ptr(m->destination, bus->unique_name))
2357                 return 0;
2358
2359         c = ordered_hashmap_remove(bus->reply_callbacks, &m->reply_cookie);
2360         if (!c)
2361                 return 0;
2362
2363         c->cookie = 0;
2364
2365         slot = container_of(c, sd_bus_slot, reply_callback);
2366
2367         if (m->n_fds > 0 && !(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)) {
2368
2369                 /* If the reply contained a file descriptor which we
2370                  * didn't want we pass an error instead. */
2371
2372                 r = bus_message_new_synthetic_error(
2373                                 bus,
2374                                 m->reply_cookie,
2375                                 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Reply message contained file descriptor"),
2376                                 &synthetic_reply);
2377                 if (r < 0)
2378                         return r;
2379
2380                 /* Copy over original timestamp */
2381                 synthetic_reply->realtime = m->realtime;
2382                 synthetic_reply->monotonic = m->monotonic;
2383                 synthetic_reply->seqnum = m->seqnum;
2384
2385                 r = bus_seal_synthetic_message(bus, synthetic_reply);
2386                 if (r < 0)
2387                         return r;
2388
2389                 m = synthetic_reply;
2390         } else {
2391                 r = sd_bus_message_rewind(m, true);
2392                 if (r < 0)
2393                         return r;
2394         }
2395
2396         if (c->timeout != 0) {
2397                 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2398                 c->timeout = 0;
2399         }
2400
2401         bus->current_slot = sd_bus_slot_ref(slot);
2402         bus->current_handler = c->callback;
2403         bus->current_userdata = slot->userdata;
2404         r = c->callback(m, slot->userdata, &error_buffer);
2405         bus->current_userdata = NULL;
2406         bus->current_handler = NULL;
2407         bus->current_slot = NULL;
2408
2409         if (slot->floating) {
2410                 bus_slot_disconnect(slot);
2411                 sd_bus_slot_unref(slot);
2412         }
2413
2414         sd_bus_slot_unref(slot);
2415
2416         return bus_maybe_reply_error(m, r, &error_buffer);
2417 }
2418
2419 static int process_filter(sd_bus *bus, sd_bus_message *m) {
2420         _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2421         struct filter_callback *l;
2422         int r;
2423
2424         assert(bus);
2425         assert(m);
2426
2427         do {
2428                 bus->filter_callbacks_modified = false;
2429
2430                 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
2431                         sd_bus_slot *slot;
2432
2433                         if (bus->filter_callbacks_modified)
2434                                 break;
2435
2436                         /* Don't run this more than once per iteration */
2437                         if (l->last_iteration == bus->iteration_counter)
2438                                 continue;
2439
2440                         l->last_iteration = bus->iteration_counter;
2441
2442                         r = sd_bus_message_rewind(m, true);
2443                         if (r < 0)
2444                                 return r;
2445
2446                         slot = container_of(l, sd_bus_slot, filter_callback);
2447
2448                         bus->current_slot = sd_bus_slot_ref(slot);
2449                         bus->current_handler = l->callback;
2450                         bus->current_userdata = slot->userdata;
2451                         r = l->callback(m, slot->userdata, &error_buffer);
2452                         bus->current_userdata = NULL;
2453                         bus->current_handler = NULL;
2454                         bus->current_slot = sd_bus_slot_unref(slot);
2455
2456                         r = bus_maybe_reply_error(m, r, &error_buffer);
2457                         if (r != 0)
2458                                 return r;
2459
2460                 }
2461
2462         } while (bus->filter_callbacks_modified);
2463
2464         return 0;
2465 }
2466
2467 static int process_match(sd_bus *bus, sd_bus_message *m) {
2468         int r;
2469
2470         assert(bus);
2471         assert(m);
2472
2473         do {
2474                 bus->match_callbacks_modified = false;
2475
2476                 r = bus_match_run(bus, &bus->match_callbacks, m);
2477                 if (r != 0)
2478                         return r;
2479
2480         } while (bus->match_callbacks_modified);
2481
2482         return 0;
2483 }
2484
2485 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
2486         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2487         int r;
2488
2489         assert(bus);
2490         assert(m);
2491
2492         if (bus->hello_flags & KDBUS_HELLO_MONITOR)
2493                 return 0;
2494
2495         if (bus->manual_peer_interface)
2496                 return 0;
2497
2498         if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2499                 return 0;
2500
2501         if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2502                 return 0;
2503
2504         if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2505                 return 1;
2506
2507         if (streq_ptr(m->member, "Ping"))
2508                 r = sd_bus_message_new_method_return(m, &reply);
2509         else if (streq_ptr(m->member, "GetMachineId")) {
2510                 sd_id128_t id;
2511                 char sid[33];
2512
2513                 r = sd_id128_get_machine(&id);
2514                 if (r < 0)
2515                         return r;
2516
2517                 r = sd_bus_message_new_method_return(m, &reply);
2518                 if (r < 0)
2519                         return r;
2520
2521                 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2522         } else {
2523                 r = sd_bus_message_new_method_errorf(
2524                                 m, &reply,
2525                                 SD_BUS_ERROR_UNKNOWN_METHOD,
2526                                  "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2527         }
2528
2529         if (r < 0)
2530                 return r;
2531
2532         r = sd_bus_send(bus, reply, NULL);
2533         if (r < 0)
2534                 return r;
2535
2536         return 1;
2537 }
2538
2539 static int process_fd_check(sd_bus *bus, sd_bus_message *m) {
2540         assert(bus);
2541         assert(m);
2542
2543         /* If we got a message with a file descriptor which we didn't
2544          * want to accept, then let's drop it. How can this even
2545          * happen? For example, when the kernel queues a message into
2546          * an activatable names's queue which allows fds, and then is
2547          * delivered to us later even though we ourselves did not
2548          * negotiate it. */
2549
2550         if (bus->hello_flags & KDBUS_HELLO_MONITOR)
2551                 return 0;
2552
2553         if (m->n_fds <= 0)
2554                 return 0;
2555
2556         if (bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)
2557                 return 0;
2558
2559         if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2560                 return 1; /* just eat it up */
2561
2562         return sd_bus_reply_method_errorf(m, SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Message contains file descriptors, which I cannot accept. Sorry.");
2563 }
2564
2565 static int process_message(sd_bus *bus, sd_bus_message *m) {
2566         int r;
2567
2568         assert(bus);
2569         assert(m);
2570
2571         bus->current_message = m;
2572         bus->iteration_counter++;
2573
2574         log_debug_bus_message(m);
2575
2576         r = process_hello(bus, m);
2577         if (r != 0)
2578                 goto finish;
2579
2580         r = process_reply(bus, m);
2581         if (r != 0)
2582                 goto finish;
2583
2584         r = process_fd_check(bus, m);
2585         if (r != 0)
2586                 goto finish;
2587
2588         r = process_filter(bus, m);
2589         if (r != 0)
2590                 goto finish;
2591
2592         r = process_match(bus, m);
2593         if (r != 0)
2594                 goto finish;
2595
2596         r = process_builtin(bus, m);
2597         if (r != 0)
2598                 goto finish;
2599
2600         r = bus_process_object(bus, m);
2601
2602 finish:
2603         bus->current_message = NULL;
2604         return r;
2605 }
2606
2607 static int dispatch_track(sd_bus *bus) {
2608         assert(bus);
2609
2610         if (!bus->track_queue)
2611                 return 0;
2612
2613         bus_track_dispatch(bus->track_queue);
2614         return 1;
2615 }
2616
2617 static int process_running(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2618         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2619         int r;
2620
2621         assert(bus);
2622         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
2623
2624         r = process_timeout(bus);
2625         if (r != 0)
2626                 goto null_message;
2627
2628         r = dispatch_wqueue(bus);
2629         if (r != 0)
2630                 goto null_message;
2631
2632         r = dispatch_track(bus);
2633         if (r != 0)
2634                 goto null_message;
2635
2636         r = dispatch_rqueue(bus, hint_priority, priority, &m);
2637         if (r < 0)
2638                 return r;
2639         if (!m)
2640                 goto null_message;
2641
2642         r = process_message(bus, m);
2643         if (r != 0)
2644                 goto null_message;
2645
2646         if (ret) {
2647                 r = sd_bus_message_rewind(m, true);
2648                 if (r < 0)
2649                         return r;
2650
2651                 *ret = m;
2652                 m = NULL;
2653                 return 1;
2654         }
2655
2656         if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2657
2658                 log_debug("Unprocessed message call sender=%s object=%s interface=%s member=%s",
2659                           strna(sd_bus_message_get_sender(m)),
2660                           strna(sd_bus_message_get_path(m)),
2661                           strna(sd_bus_message_get_interface(m)),
2662                           strna(sd_bus_message_get_member(m)));
2663
2664                 r = sd_bus_reply_method_errorf(
2665                                 m,
2666                                 SD_BUS_ERROR_UNKNOWN_OBJECT,
2667                                 "Unknown object '%s'.", m->path);
2668                 if (r < 0)
2669                         return r;
2670         }
2671
2672         return 1;
2673
2674 null_message:
2675         if (r >= 0 && ret)
2676                 *ret = NULL;
2677
2678         return r;
2679 }
2680
2681 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2682         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2683         struct reply_callback *c;
2684         int r;
2685
2686         assert(bus);
2687         assert(bus->state == BUS_CLOSING);
2688
2689         c = ordered_hashmap_first(bus->reply_callbacks);
2690         if (c) {
2691                 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2692                 sd_bus_slot *slot;
2693
2694                 /* First, fail all outstanding method calls */
2695                 r = bus_message_new_synthetic_error(
2696                                 bus,
2697                                 c->cookie,
2698                                 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2699                                 &m);
2700                 if (r < 0)
2701                         return r;
2702
2703                 r = bus_seal_synthetic_message(bus, m);
2704                 if (r < 0)
2705                         return r;
2706
2707                 if (c->timeout != 0) {
2708                         prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2709                         c->timeout = 0;
2710                 }
2711
2712                 ordered_hashmap_remove(bus->reply_callbacks, &c->cookie);
2713                 c->cookie = 0;
2714
2715                 slot = container_of(c, sd_bus_slot, reply_callback);
2716
2717                 bus->iteration_counter++;
2718
2719                 bus->current_message = m;
2720                 bus->current_slot = sd_bus_slot_ref(slot);
2721                 bus->current_handler = c->callback;
2722                 bus->current_userdata = slot->userdata;
2723                 r = c->callback(m, slot->userdata, &error_buffer);
2724                 bus->current_userdata = NULL;
2725                 bus->current_handler = NULL;
2726                 bus->current_slot = NULL;
2727                 bus->current_message = NULL;
2728
2729                 if (slot->floating) {
2730                         bus_slot_disconnect(slot);
2731                         sd_bus_slot_unref(slot);
2732                 }
2733
2734                 sd_bus_slot_unref(slot);
2735
2736                 return bus_maybe_reply_error(m, r, &error_buffer);
2737         }
2738
2739         /* Then, synthesize a Disconnected message */
2740         r = sd_bus_message_new_signal(
2741                         bus,
2742                         &m,
2743                         "/org/freedesktop/DBus/Local",
2744                         "org.freedesktop.DBus.Local",
2745                         "Disconnected");
2746         if (r < 0)
2747                 return r;
2748
2749         bus_message_set_sender_local(bus, m);
2750
2751         r = bus_seal_synthetic_message(bus, m);
2752         if (r < 0)
2753                 return r;
2754
2755         sd_bus_close(bus);
2756
2757         bus->current_message = m;
2758         bus->iteration_counter++;
2759
2760         r = process_filter(bus, m);
2761         if (r != 0)
2762                 goto finish;
2763
2764         r = process_match(bus, m);
2765         if (r != 0)
2766                 goto finish;
2767
2768         if (ret) {
2769                 *ret = m;
2770                 m = NULL;
2771         }
2772
2773         r = 1;
2774
2775 finish:
2776         bus->current_message = NULL;
2777
2778         return r;
2779 }
2780
2781 static int bus_process_internal(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2782         BUS_DONT_DESTROY(bus);
2783         int r;
2784
2785         /* Returns 0 when we didn't do anything. This should cause the
2786          * caller to invoke sd_bus_wait() before returning the next
2787          * time. Returns > 0 when we did something, which possibly
2788          * means *ret is filled in with an unprocessed message. */
2789
2790         assert_return(bus, -EINVAL);
2791         assert_return(!bus_pid_changed(bus), -ECHILD);
2792
2793         /* We don't allow recursively invoking sd_bus_process(). */
2794         assert_return(!bus->current_message, -EBUSY);
2795         assert(!bus->current_slot);
2796
2797         switch (bus->state) {
2798
2799         case BUS_UNSET:
2800                 return -ENOTCONN;
2801
2802         case BUS_CLOSED:
2803                 return -ECONNRESET;
2804
2805         case BUS_OPENING:
2806                 r = bus_socket_process_opening(bus);
2807                 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2808                         bus_enter_closing(bus);
2809                         r = 1;
2810                 } else if (r < 0)
2811                         return r;
2812                 if (ret)
2813                         *ret = NULL;
2814                 return r;
2815
2816         case BUS_AUTHENTICATING:
2817                 r = bus_socket_process_authenticating(bus);
2818                 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2819                         bus_enter_closing(bus);
2820                         r = 1;
2821                 } else if (r < 0)
2822                         return r;
2823
2824                 if (ret)
2825                         *ret = NULL;
2826
2827                 return r;
2828
2829         case BUS_RUNNING:
2830         case BUS_HELLO:
2831                 r = process_running(bus, hint_priority, priority, ret);
2832                 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2833                         bus_enter_closing(bus);
2834                         r = 1;
2835
2836                         if (ret)
2837                                 *ret = NULL;
2838                 }
2839
2840                 return r;
2841
2842         case BUS_CLOSING:
2843                 return process_closing(bus, ret);
2844         }
2845
2846         assert_not_reached("Unknown state");
2847 }
2848
2849 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2850         return bus_process_internal(bus, false, 0, ret);
2851 }
2852
2853 /// UNNEEDED by elogind
2854 #if 0
2855 _public_ int sd_bus_process_priority(sd_bus *bus, int64_t priority, sd_bus_message **ret) {
2856         return bus_process_internal(bus, true, priority, ret);
2857 }
2858 #endif // 0
2859
2860 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2861         struct pollfd p[2] = {};
2862         int r, e, n;
2863         struct timespec ts;
2864         usec_t m = USEC_INFINITY;
2865
2866         assert(bus);
2867
2868         if (bus->state == BUS_CLOSING)
2869                 return 1;
2870
2871         if (!BUS_IS_OPEN(bus->state))
2872                 return -ENOTCONN;
2873
2874         e = sd_bus_get_events(bus);
2875         if (e < 0)
2876                 return e;
2877
2878         if (need_more)
2879                 /* The caller really needs some more data, he doesn't
2880                  * care about what's already read, or any timeouts
2881                  * except its own. */
2882                 e |= POLLIN;
2883         else {
2884                 usec_t until;
2885                 /* The caller wants to process if there's something to
2886                  * process, but doesn't care otherwise */
2887
2888                 r = sd_bus_get_timeout(bus, &until);
2889                 if (r < 0)
2890                         return r;
2891                 if (r > 0) {
2892                         usec_t nw;
2893                         nw = now(CLOCK_MONOTONIC);
2894                         m = until > nw ? until - nw : 0;
2895                 }
2896         }
2897
2898         if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
2899                 m = timeout_usec;
2900
2901         p[0].fd = bus->input_fd;
2902         if (bus->output_fd == bus->input_fd) {
2903                 p[0].events = e;
2904                 n = 1;
2905         } else {
2906                 p[0].events = e & POLLIN;
2907                 p[1].fd = bus->output_fd;
2908                 p[1].events = e & POLLOUT;
2909                 n = 2;
2910         }
2911
2912         r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
2913         if (r < 0)
2914                 return -errno;
2915
2916         return r > 0 ? 1 : 0;
2917 }
2918
2919 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
2920
2921         assert_return(bus, -EINVAL);
2922         assert_return(!bus_pid_changed(bus), -ECHILD);
2923
2924         if (bus->state == BUS_CLOSING)
2925                 return 0;
2926
2927         if (!BUS_IS_OPEN(bus->state))
2928                 return -ENOTCONN;
2929
2930         if (bus->rqueue_size > 0)
2931                 return 0;
2932
2933         return bus_poll(bus, false, timeout_usec);
2934 }
2935
2936 _public_ int sd_bus_flush(sd_bus *bus) {
2937         int r;
2938
2939         assert_return(bus, -EINVAL);
2940         assert_return(!bus_pid_changed(bus), -ECHILD);
2941
2942         if (bus->state == BUS_CLOSING)
2943                 return 0;
2944
2945         if (!BUS_IS_OPEN(bus->state))
2946                 return -ENOTCONN;
2947
2948         r = bus_ensure_running(bus);
2949         if (r < 0)
2950                 return r;
2951
2952         if (bus->wqueue_size <= 0)
2953                 return 0;
2954
2955         for (;;) {
2956                 r = dispatch_wqueue(bus);
2957                 if (r < 0) {
2958                         if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2959                                 bus_enter_closing(bus);
2960                                 return -ECONNRESET;
2961                         }
2962
2963                         return r;
2964                 }
2965
2966                 if (bus->wqueue_size <= 0)
2967                         return 0;
2968
2969                 r = bus_poll(bus, false, (uint64_t) -1);
2970                 if (r < 0)
2971                         return r;
2972         }
2973 }
2974
2975 /// UNNEEDED by elogind
2976 #if 0
2977 _public_ int sd_bus_add_filter(
2978                 sd_bus *bus,
2979                 sd_bus_slot **slot,
2980                 sd_bus_message_handler_t callback,
2981                 void *userdata) {
2982
2983         sd_bus_slot *s;
2984
2985         assert_return(bus, -EINVAL);
2986         assert_return(callback, -EINVAL);
2987         assert_return(!bus_pid_changed(bus), -ECHILD);
2988
2989         s = bus_slot_allocate(bus, !slot, BUS_FILTER_CALLBACK, sizeof(struct filter_callback), userdata);
2990         if (!s)
2991                 return -ENOMEM;
2992
2993         s->filter_callback.callback = callback;
2994
2995         bus->filter_callbacks_modified = true;
2996         LIST_PREPEND(callbacks, bus->filter_callbacks, &s->filter_callback);
2997
2998         if (slot)
2999                 *slot = s;
3000
3001         return 0;
3002 }
3003 #endif // 0
3004
3005 _public_ int sd_bus_add_match(
3006                 sd_bus *bus,
3007                 sd_bus_slot **slot,
3008                 const char *match,
3009                 sd_bus_message_handler_t callback,
3010                 void *userdata) {
3011
3012         struct bus_match_component *components = NULL;
3013         unsigned n_components = 0;
3014         sd_bus_slot *s = NULL;
3015         int r = 0;
3016
3017         assert_return(bus, -EINVAL);
3018         assert_return(match, -EINVAL);
3019         assert_return(!bus_pid_changed(bus), -ECHILD);
3020
3021         r = bus_match_parse(match, &components, &n_components);
3022         if (r < 0)
3023                 goto finish;
3024
3025         s = bus_slot_allocate(bus, !slot, BUS_MATCH_CALLBACK, sizeof(struct match_callback), userdata);
3026         if (!s) {
3027                 r = -ENOMEM;
3028                 goto finish;
3029         }
3030
3031         s->match_callback.callback = callback;
3032         s->match_callback.cookie = ++bus->match_cookie;
3033
3034         if (bus->bus_client) {
3035                 enum bus_match_scope scope;
3036
3037                 scope = bus_match_get_scope(components, n_components);
3038
3039                 /* Do not install server-side matches for matches
3040                  * against the local service, interface or bus
3041                  * path. */
3042                 if (scope != BUS_MATCH_LOCAL) {
3043
3044                         if (!bus->is_kernel) {
3045                                 /* When this is not a kernel transport, we
3046                                  * store the original match string, so that we
3047                                  * can use it to remove the match again */
3048
3049                                 s->match_callback.match_string = strdup(match);
3050                                 if (!s->match_callback.match_string) {
3051                                         r = -ENOMEM;
3052                                         goto finish;
3053                                 }
3054                         }
3055
3056                         r = bus_add_match_internal(bus, s->match_callback.match_string, components, n_components, s->match_callback.cookie);
3057                         if (r < 0)
3058                                 goto finish;
3059
3060                         s->match_added = true;
3061                 }
3062         }
3063
3064         bus->match_callbacks_modified = true;
3065         r = bus_match_add(&bus->match_callbacks, components, n_components, &s->match_callback);
3066         if (r < 0)
3067                 goto finish;
3068
3069         if (slot)
3070                 *slot = s;
3071         s = NULL;
3072
3073 finish:
3074         bus_match_parse_free(components, n_components);
3075         sd_bus_slot_unref(s);
3076
3077         return r;
3078 }
3079
3080 /// UNNEEDED by elogind
3081 #if 0
3082 int bus_remove_match_by_string(
3083                 sd_bus *bus,
3084                 const char *match,
3085                 sd_bus_message_handler_t callback,
3086                 void *userdata) {
3087
3088         struct bus_match_component *components = NULL;
3089         unsigned n_components = 0;
3090         struct match_callback *c;
3091         int r = 0;
3092
3093         assert_return(bus, -EINVAL);
3094         assert_return(match, -EINVAL);
3095         assert_return(!bus_pid_changed(bus), -ECHILD);
3096
3097         r = bus_match_parse(match, &components, &n_components);
3098         if (r < 0)
3099                 goto finish;
3100
3101         r = bus_match_find(&bus->match_callbacks, components, n_components, NULL, NULL, &c);
3102         if (r <= 0)
3103                 goto finish;
3104
3105         sd_bus_slot_unref(container_of(c, sd_bus_slot, match_callback));
3106
3107 finish:
3108         bus_match_parse_free(components, n_components);
3109
3110         return r;
3111 }
3112 #endif // 0
3113
3114 bool bus_pid_changed(sd_bus *bus) {
3115         assert(bus);
3116
3117         /* We don't support people creating a bus connection and
3118          * keeping it around over a fork(). Let's complain. */
3119
3120         return bus->original_pid != getpid();
3121 }
3122
3123 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
3124         sd_bus *bus = userdata;
3125         int r;
3126
3127         assert(bus);
3128
3129         r = sd_bus_process(bus, NULL);
3130         if (r < 0)
3131                 return r;
3132
3133         return 1;
3134 }
3135
3136 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
3137         sd_bus *bus = userdata;
3138         int r;
3139
3140         assert(bus);
3141
3142         r = sd_bus_process(bus, NULL);
3143         if (r < 0)
3144                 return r;
3145
3146         return 1;
3147 }
3148
3149 static int prepare_callback(sd_event_source *s, void *userdata) {
3150         sd_bus *bus = userdata;
3151         int r, e;
3152         usec_t until;
3153
3154         assert(s);
3155         assert(bus);
3156
3157         e = sd_bus_get_events(bus);
3158         if (e < 0)
3159                 return e;
3160
3161         if (bus->output_fd != bus->input_fd) {
3162
3163                 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
3164                 if (r < 0)
3165                         return r;
3166
3167                 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
3168                 if (r < 0)
3169                         return r;
3170         } else {
3171                 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
3172                 if (r < 0)
3173                         return r;
3174         }
3175
3176         r = sd_bus_get_timeout(bus, &until);
3177         if (r < 0)
3178                 return r;
3179         if (r > 0) {
3180                 int j;
3181
3182                 j = sd_event_source_set_time(bus->time_event_source, until);
3183                 if (j < 0)
3184                         return j;
3185         }
3186
3187         r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
3188         if (r < 0)
3189                 return r;
3190
3191         return 1;
3192 }
3193
3194 static int quit_callback(sd_event_source *event, void *userdata) {
3195         sd_bus *bus = userdata;
3196
3197         assert(event);
3198
3199         sd_bus_flush(bus);
3200         sd_bus_close(bus);
3201
3202         return 1;
3203 }
3204
3205 static int attach_io_events(sd_bus *bus) {
3206         int r;
3207
3208         assert(bus);
3209
3210         if (bus->input_fd < 0)
3211                 return 0;
3212
3213         if (!bus->event)
3214                 return 0;
3215
3216         if (!bus->input_io_event_source) {
3217                 r = sd_event_add_io(bus->event, &bus->input_io_event_source, bus->input_fd, 0, io_callback, bus);
3218                 if (r < 0)
3219                         return r;
3220
3221                 r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
3222                 if (r < 0)
3223                         return r;
3224
3225                 r = sd_event_source_set_priority(bus->input_io_event_source, bus->event_priority);
3226                 if (r < 0)
3227                         return r;
3228
3229                 r = sd_event_source_set_description(bus->input_io_event_source, "bus-input");
3230         } else
3231                 r = sd_event_source_set_io_fd(bus->input_io_event_source, bus->input_fd);
3232
3233         if (r < 0)
3234                 return r;
3235
3236         if (bus->output_fd != bus->input_fd) {
3237                 assert(bus->output_fd >= 0);
3238
3239                 if (!bus->output_io_event_source) {
3240                         r = sd_event_add_io(bus->event, &bus->output_io_event_source, bus->output_fd, 0, io_callback, bus);
3241                         if (r < 0)
3242                                 return r;
3243
3244                         r = sd_event_source_set_priority(bus->output_io_event_source, bus->event_priority);
3245                         if (r < 0)
3246                                 return r;
3247
3248                         r = sd_event_source_set_description(bus->input_io_event_source, "bus-output");
3249                 } else
3250                         r = sd_event_source_set_io_fd(bus->output_io_event_source, bus->output_fd);
3251
3252                 if (r < 0)
3253                         return r;
3254         }
3255
3256         return 0;
3257 }
3258
3259 static void detach_io_events(sd_bus *bus) {
3260         assert(bus);
3261
3262         if (bus->input_io_event_source) {
3263                 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
3264                 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
3265         }
3266
3267         if (bus->output_io_event_source) {
3268                 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
3269                 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
3270         }
3271 }
3272
3273 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
3274         int r;
3275
3276         assert_return(bus, -EINVAL);
3277         assert_return(!bus->event, -EBUSY);
3278
3279         assert(!bus->input_io_event_source);
3280         assert(!bus->output_io_event_source);
3281         assert(!bus->time_event_source);
3282
3283         if (event)
3284                 bus->event = sd_event_ref(event);
3285         else  {
3286                 r = sd_event_default(&bus->event);
3287                 if (r < 0)
3288                         return r;
3289         }
3290
3291         bus->event_priority = priority;
3292
3293         r = sd_event_add_time(bus->event, &bus->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, bus);
3294         if (r < 0)
3295                 goto fail;
3296
3297         r = sd_event_source_set_priority(bus->time_event_source, priority);
3298         if (r < 0)
3299                 goto fail;
3300
3301         r = sd_event_source_set_description(bus->time_event_source, "bus-time");
3302         if (r < 0)
3303                 goto fail;
3304
3305         r = sd_event_add_exit(bus->event, &bus->quit_event_source, quit_callback, bus);
3306         if (r < 0)
3307                 goto fail;
3308
3309         r = sd_event_source_set_description(bus->quit_event_source, "bus-exit");
3310         if (r < 0)
3311                 goto fail;
3312
3313         r = attach_io_events(bus);
3314         if (r < 0)
3315                 goto fail;
3316
3317         return 0;
3318
3319 fail:
3320         sd_bus_detach_event(bus);
3321         return r;
3322 }
3323
3324 _public_ int sd_bus_detach_event(sd_bus *bus) {
3325         assert_return(bus, -EINVAL);
3326
3327         if (!bus->event)
3328                 return 0;
3329
3330         detach_io_events(bus);
3331
3332         if (bus->time_event_source) {
3333                 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
3334                 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
3335         }
3336
3337         if (bus->quit_event_source) {
3338                 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
3339                 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
3340         }
3341
3342         bus->event = sd_event_unref(bus->event);
3343         return 1;
3344 }
3345
3346 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
3347         assert_return(bus, NULL);
3348
3349         return bus->event;
3350 }
3351
3352 _public_ sd_bus_message* sd_bus_get_current_message(sd_bus *bus) {
3353         assert_return(bus, NULL);
3354
3355         return bus->current_message;
3356 }
3357
3358 /// UNNEEDED by elogind
3359 #if 0
3360 _public_ sd_bus_slot* sd_bus_get_current_slot(sd_bus *bus) {
3361         assert_return(bus, NULL);
3362
3363         return bus->current_slot;
3364 }
3365 #endif // 0
3366
3367 _public_ sd_bus_message_handler_t sd_bus_get_current_handler(sd_bus *bus) {
3368         assert_return(bus, NULL);
3369
3370         return bus->current_handler;
3371 }
3372
3373 _public_ void* sd_bus_get_current_userdata(sd_bus *bus) {
3374         assert_return(bus, NULL);
3375
3376         return bus->current_userdata;
3377 }
3378
3379 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
3380         sd_bus *b = NULL;
3381         int r;
3382
3383         assert(bus_open);
3384         assert(default_bus);
3385
3386         if (!ret)
3387                 return !!*default_bus;
3388
3389         if (*default_bus) {
3390                 *ret = sd_bus_ref(*default_bus);
3391                 return 0;
3392         }
3393
3394         r = bus_open(&b);
3395         if (r < 0)
3396                 return r;
3397
3398         b->default_bus_ptr = default_bus;
3399         b->tid = gettid();
3400         *default_bus = b;
3401
3402         *ret = b;
3403         return 1;
3404 }
3405
3406 _public_ int sd_bus_default_system(sd_bus **ret) {
3407         return bus_default(sd_bus_open_system, &default_system_bus, ret);
3408 }
3409
3410
3411 _public_ int sd_bus_default_user(sd_bus **ret) {
3412 /// elogind does not support user buses
3413 #if 0
3414         return bus_default(sd_bus_open_user, &default_user_bus, ret);
3415 #else
3416         return sd_bus_default_system(ret);
3417 #endif // 0
3418 }
3419
3420 _public_ int sd_bus_default(sd_bus **ret) {
3421
3422         const char *e;
3423
3424         /* Let's try our best to reuse another cached connection. If
3425          * the starter bus type is set, connect via our normal
3426          * connection logic, ignoring $DBUS_STARTER_ADDRESS, so that
3427          * we can share the connection with the user/system default
3428          * bus. */
3429
3430         e = secure_getenv("DBUS_STARTER_BUS_TYPE");
3431         if (e) {
3432                 if (streq(e, "system"))
3433                         return sd_bus_default_system(ret);
3434 /// elogind does not support systemd units
3435 #if 0
3436                 else if (STR_IN_SET(e, "user", "session"))
3437                         return sd_bus_default_user(ret);
3438 #endif // 0
3439         }
3440
3441         /* No type is specified, so we have not other option than to
3442          * use the starter address if it is set. */
3443
3444         e = secure_getenv("DBUS_STARTER_ADDRESS");
3445         if (e) {
3446
3447                 return bus_default(sd_bus_open, &default_starter_bus, ret);
3448         }
3449
3450         /* Finally, if nothing is set use the cached connection for
3451          * the right scope */
3452
3453 /// elogind does not support systemd units
3454 #if 0
3455         if (cg_pid_get_owner_uid(0, NULL) >= 0)
3456                 return sd_bus_default_user(ret);
3457         else
3458 #endif // 0
3459         return sd_bus_default_system(ret);
3460 }
3461
3462 /// UNNEEDED by elogind
3463 #if 0
3464 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
3465         assert_return(b, -EINVAL);
3466         assert_return(tid, -EINVAL);
3467         assert_return(!bus_pid_changed(b), -ECHILD);
3468
3469         if (b->tid != 0) {
3470                 *tid = b->tid;
3471                 return 0;
3472         }
3473
3474         if (b->event)
3475                 return sd_event_get_tid(b->event, tid);
3476
3477         return -ENXIO;
3478 }
3479
3480 _public_ int sd_bus_path_encode(const char *prefix, const char *external_id, char **ret_path) {
3481         _cleanup_free_ char *e = NULL;
3482         char *ret;
3483
3484         assert_return(object_path_is_valid(prefix), -EINVAL);
3485         assert_return(external_id, -EINVAL);
3486         assert_return(ret_path, -EINVAL);
3487
3488         e = bus_label_escape(external_id);
3489         if (!e)
3490                 return -ENOMEM;
3491
3492         ret = strjoin(prefix, "/", e, NULL);
3493         if (!ret)
3494                 return -ENOMEM;
3495
3496         *ret_path = ret;
3497         return 0;
3498 }
3499
3500 _public_ int sd_bus_path_decode(const char *path, const char *prefix, char **external_id) {
3501         const char *e;
3502         char *ret;
3503
3504         assert_return(object_path_is_valid(path), -EINVAL);
3505         assert_return(object_path_is_valid(prefix), -EINVAL);
3506         assert_return(external_id, -EINVAL);
3507
3508         e = object_path_startswith(path, prefix);
3509         if (!e) {
3510                 *external_id = NULL;
3511                 return 0;
3512         }
3513
3514         ret = bus_label_unescape(e);
3515         if (!ret)
3516                 return -ENOMEM;
3517
3518         *external_id = ret;
3519         return 1;
3520 }
3521
3522 _public_ int sd_bus_path_encode_many(char **out, const char *path_template, ...) {
3523         _cleanup_strv_free_ char **labels = NULL;
3524         char *path, *path_pos, **label_pos;
3525         const char *sep, *template_pos;
3526         size_t path_length;
3527         va_list list;
3528         int r;
3529
3530         assert_return(out, -EINVAL);
3531         assert_return(path_template, -EINVAL);
3532
3533         path_length = strlen(path_template);
3534
3535         va_start(list, path_template);
3536         for (sep = strchr(path_template, '%'); sep; sep = strchr(sep + 1, '%')) {
3537                 const char *arg;
3538                 char *label;
3539
3540                 arg = va_arg(list, const char *);
3541                 if (!arg) {
3542                         va_end(list);
3543                         return -EINVAL;
3544                 }
3545
3546                 label = bus_label_escape(arg);
3547                 if (!label) {
3548                         va_end(list);
3549                         return -ENOMEM;
3550                 }
3551
3552                 r = strv_consume(&labels, label);
3553                 if (r < 0) {
3554                         va_end(list);
3555                         return r;
3556                 }
3557
3558                 /* add label length, but account for the format character */
3559                 path_length += strlen(label) - 1;
3560         }
3561         va_end(list);
3562
3563         path = malloc(path_length + 1);
3564         if (!path)
3565                 return -ENOMEM;
3566
3567         path_pos = path;
3568         label_pos = labels;
3569
3570         for (template_pos = path_template; *template_pos; ) {
3571                 sep = strchrnul(template_pos, '%');
3572                 path_pos = mempcpy(path_pos, template_pos, sep - template_pos);
3573                 if (!*sep)
3574                         break;
3575
3576                 path_pos = stpcpy(path_pos, *label_pos++);
3577                 template_pos = sep + 1;
3578         }
3579
3580         *path_pos = 0;
3581         *out = path;
3582         return 0;
3583 }
3584
3585 _public_ int sd_bus_path_decode_many(const char *path, const char *path_template, ...) {
3586         _cleanup_strv_free_ char **labels = NULL;
3587         const char *template_pos, *path_pos;
3588         char **label_pos;
3589         va_list list;
3590         int r;
3591
3592         /*
3593          * This decodes an object-path based on a template argument. The
3594          * template consists of a verbatim path, optionally including special
3595          * directives:
3596          *
3597          *   - Each occurrence of '%' in the template matches an arbitrary
3598          *     substring of a label in the given path. At most one such
3599          *     directive is allowed per label. For each such directive, the
3600          *     caller must provide an output parameter (char **) via va_arg. If
3601          *     NULL is passed, the given label is verified, but not returned.
3602          *     For each matched label, the *decoded* label is stored in the
3603          *     passed output argument, and the caller is responsible to free
3604          *     it. Note that the output arguments are only modified if the
3605          *     actualy path matched the template. Otherwise, they're left
3606          *     untouched.
3607          *
3608          * This function returns <0 on error, 0 if the path does not match the
3609          * template, 1 if it matched.
3610          */
3611
3612         assert_return(path, -EINVAL);
3613         assert_return(path_template, -EINVAL);
3614
3615         path_pos = path;
3616
3617         for (template_pos = path_template; *template_pos; ) {
3618                 const char *sep;
3619                 size_t length;
3620                 char *label;
3621
3622                 /* verify everything until the next '%' matches verbatim */
3623                 sep = strchrnul(template_pos, '%');
3624                 length = sep - template_pos;
3625                 if (strncmp(path_pos, template_pos, length))
3626                         return 0;
3627
3628                 path_pos += length;
3629                 template_pos += length;
3630
3631                 if (!*template_pos)
3632                         break;
3633
3634                 /* We found the next '%' character. Everything up until here
3635                  * matched. We now skip ahead to the end of this label and make
3636                  * sure it matches the tail of the label in the path. Then we
3637                  * decode the string in-between and save it for later use. */
3638
3639                 ++template_pos; /* skip over '%' */
3640
3641                 sep = strchrnul(template_pos, '/');
3642                 length = sep - template_pos; /* length of suffix to match verbatim */
3643
3644                 /* verify the suffixes match */
3645                 sep = strchrnul(path_pos, '/');
3646                 if (sep - path_pos < (ssize_t)length ||
3647                     strncmp(sep - length, template_pos, length))
3648                         return 0;
3649
3650                 template_pos += length; /* skip over matched label */
3651                 length = sep - path_pos - length; /* length of sub-label to decode */
3652
3653                 /* store unescaped label for later use */
3654                 label = bus_label_unescape_n(path_pos, length);
3655                 if (!label)
3656                         return -ENOMEM;
3657
3658                 r = strv_consume(&labels, label);
3659                 if (r < 0)
3660                         return r;
3661
3662                 path_pos = sep; /* skip decoded label and suffix */
3663         }
3664
3665         /* end of template must match end of path */
3666         if (*path_pos)
3667                 return 0;
3668
3669         /* copy the labels over to the caller */
3670         va_start(list, path_template);
3671         for (label_pos = labels; label_pos && *label_pos; ++label_pos) {
3672                 char **arg;
3673
3674                 arg = va_arg(list, char **);
3675                 if (arg)
3676                         *arg = *label_pos;
3677                 else
3678                         free(*label_pos);
3679         }
3680         va_end(list);
3681
3682         free(labels);
3683         labels = NULL;
3684         return 1;
3685 }
3686
3687 _public_ int sd_bus_try_close(sd_bus *bus) {
3688         int r;
3689
3690         assert_return(bus, -EINVAL);
3691         assert_return(!bus_pid_changed(bus), -ECHILD);
3692
3693         if (!bus->is_kernel)
3694                 return -EOPNOTSUPP;
3695
3696         if (!BUS_IS_OPEN(bus->state))
3697                 return -ENOTCONN;
3698
3699         if (bus->rqueue_size > 0)
3700                 return -EBUSY;
3701
3702         if (bus->wqueue_size > 0)
3703                 return -EBUSY;
3704
3705         r = bus_kernel_try_close(bus);
3706         if (r < 0)
3707                 return r;
3708
3709         sd_bus_close(bus);
3710         return 0;
3711 }
3712
3713 _public_ int sd_bus_get_description(sd_bus *bus, const char **description) {
3714         assert_return(bus, -EINVAL);
3715         assert_return(description, -EINVAL);
3716         assert_return(bus->description, -ENXIO);
3717         assert_return(!bus_pid_changed(bus), -ECHILD);
3718
3719         *description = bus->description;
3720         return 0;
3721 }
3722 #endif // 0
3723
3724 int bus_get_root_path(sd_bus *bus) {
3725         int r;
3726
3727         if (bus->cgroup_root)
3728                 return 0;
3729
3730         r = cg_get_root_path(&bus->cgroup_root);
3731         if (r == -ENOENT) {
3732                 bus->cgroup_root = strdup("/");
3733                 if (!bus->cgroup_root)
3734                         return -ENOMEM;
3735
3736                 r = 0;
3737         }
3738
3739         return r;
3740 }
3741
3742 /// UNNEEDED by elogind
3743 #if 0
3744 _public_ int sd_bus_get_scope(sd_bus *bus, const char **scope) {
3745         int r;
3746
3747         assert_return(bus, -EINVAL);
3748         assert_return(scope, -EINVAL);
3749         assert_return(!bus_pid_changed(bus), -ECHILD);
3750
3751         if (bus->is_kernel) {
3752                 _cleanup_free_ char *n = NULL;
3753                 const char *dash;
3754
3755                 r = bus_kernel_get_bus_name(bus, &n);
3756                 if (r < 0)
3757                         return r;
3758
3759                 if (streq(n, "0-system")) {
3760                         *scope = "system";
3761                         return 0;
3762                 }
3763
3764                 dash = strchr(n, '-');
3765                 if (streq_ptr(dash, "-user")) {
3766                         *scope = "user";
3767                         return 0;
3768                 }
3769         }
3770
3771         if (bus->is_user) {
3772                 *scope = "user";
3773                 return 0;
3774         }
3775
3776         if (bus->is_system) {
3777                 *scope = "system";
3778                 return 0;
3779         }
3780
3781         return -ENODATA;
3782 }
3783
3784 _public_ int sd_bus_get_address(sd_bus *bus, const char **address) {
3785
3786         assert_return(bus, -EINVAL);
3787         assert_return(address, -EINVAL);
3788         assert_return(!bus_pid_changed(bus), -ECHILD);
3789
3790         if (bus->address) {
3791                 *address = bus->address;
3792                 return 0;
3793         }
3794
3795         return -ENODATA;
3796 }
3797
3798 _public_ int sd_bus_get_creds_mask(sd_bus *bus, uint64_t *mask) {
3799         assert_return(bus, -EINVAL);
3800         assert_return(mask, -EINVAL);
3801         assert_return(!bus_pid_changed(bus), -ECHILD);
3802
3803         *mask = bus->creds_mask;
3804         return 0;
3805 }
3806
3807 _public_ int sd_bus_is_bus_client(sd_bus *bus) {
3808         assert_return(bus, -EINVAL);
3809         assert_return(!bus_pid_changed(bus), -ECHILD);
3810
3811         return bus->bus_client;
3812 }
3813
3814 _public_ int sd_bus_is_server(sd_bus *bus) {
3815         assert_return(bus, -EINVAL);
3816         assert_return(!bus_pid_changed(bus), -ECHILD);
3817
3818         return bus->is_server;
3819 }
3820
3821 _public_ int sd_bus_is_anonymous(sd_bus *bus) {
3822         assert_return(bus, -EINVAL);
3823         assert_return(!bus_pid_changed(bus), -ECHILD);
3824
3825         return bus->anonymous_auth;
3826 }
3827
3828 _public_ int sd_bus_is_trusted(sd_bus *bus) {
3829         assert_return(bus, -EINVAL);
3830         assert_return(!bus_pid_changed(bus), -ECHILD);
3831
3832         return bus->trusted;
3833 }
3834
3835 _public_ int sd_bus_is_monitor(sd_bus *bus) {
3836         assert_return(bus, -EINVAL);
3837         assert_return(!bus_pid_changed(bus), -ECHILD);
3838
3839         return !!(bus->hello_flags & KDBUS_HELLO_MONITOR);
3840 }
3841
3842 static void flush_close(sd_bus *bus) {
3843         if (!bus)
3844                 return;
3845
3846         /* Flushes and closes the specified bus. We take a ref before,
3847          * to ensure the flushing does not cause the bus to be
3848          * unreferenced. */
3849
3850         sd_bus_flush_close_unref(sd_bus_ref(bus));
3851 }
3852
3853 _public_ void sd_bus_default_flush_close(void) {
3854         flush_close(default_starter_bus);
3855         flush_close(default_user_bus);
3856         flush_close(default_system_bus);
3857 }
3858 #endif // 0