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