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