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