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