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