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