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