chiark / gitweb /
bus: fix unitialized variable access in error path
[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, 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, 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         sd_bus_slot *slot;
2094         usec_t n;
2095         int r;
2096
2097         assert(bus);
2098
2099         c = prioq_peek(bus->reply_callbacks_prioq);
2100         if (!c)
2101                 return 0;
2102
2103         n = now(CLOCK_MONOTONIC);
2104         if (c->timeout > n)
2105                 return 0;
2106
2107         r = bus_message_new_synthetic_error(
2108                         bus,
2109                         c->cookie,
2110                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
2111                         &m);
2112         if (r < 0)
2113                 return r;
2114
2115         m->sender = "org.freedesktop.DBus";
2116
2117         r = bus_seal_synthetic_message(bus, m);
2118         if (r < 0)
2119                 return r;
2120
2121         assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
2122         c->timeout = 0;
2123
2124         hashmap_remove(bus->reply_callbacks, &c->cookie);
2125         c->cookie = 0;
2126
2127         slot = container_of(c, sd_bus_slot, reply_callback);
2128
2129         bus->iteration_counter ++;
2130
2131         bus->current_message = m;
2132         bus->current_slot = sd_bus_slot_ref(slot);
2133         r = c->callback(bus, m, slot->userdata, &error_buffer);
2134         bus->current_slot = sd_bus_slot_unref(slot);
2135         bus->current_message = NULL;
2136
2137         if (slot->floating) {
2138                 bus_slot_disconnect(slot);
2139                 sd_bus_slot_unref(slot);
2140         }
2141
2142         return bus_maybe_reply_error(m, r, &error_buffer);
2143 }
2144
2145 static int process_hello(sd_bus *bus, sd_bus_message *m) {
2146         assert(bus);
2147         assert(m);
2148
2149         if (bus->state != BUS_HELLO)
2150                 return 0;
2151
2152         /* Let's make sure the first message on the bus is the HELLO
2153          * reply. But note that we don't actually parse the message
2154          * here (we leave that to the usual handling), we just verify
2155          * we don't let any earlier msg through. */
2156
2157         if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2158             m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2159                 return -EIO;
2160
2161         if (m->reply_cookie != 1)
2162                 return -EIO;
2163
2164         return 0;
2165 }
2166
2167 static int process_reply(sd_bus *bus, sd_bus_message *m) {
2168         _cleanup_bus_message_unref_ sd_bus_message *synthetic_reply = NULL;
2169         _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2170         struct reply_callback *c;
2171         sd_bus_slot *slot;
2172         int r;
2173
2174         assert(bus);
2175         assert(m);
2176
2177         if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
2178             m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
2179                 return 0;
2180
2181         if (bus->is_kernel && (bus->hello_flags & KDBUS_HELLO_MONITOR))
2182                 return 0;
2183
2184         if (m->destination && bus->unique_name && !streq_ptr(m->destination, bus->unique_name))
2185                 return 0;
2186
2187         c = hashmap_remove(bus->reply_callbacks, &m->reply_cookie);
2188         if (!c)
2189                 return 0;
2190
2191         c->cookie = 0;
2192
2193         slot = container_of(c, sd_bus_slot, reply_callback);
2194
2195         if (m->n_fds > 0 && !(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)) {
2196
2197                 /* If the reply contained a file descriptor which we
2198                  * didn't want we pass an error instead. */
2199
2200                 r = bus_message_new_synthetic_error(
2201                                 bus,
2202                                 m->reply_cookie,
2203                                 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Reply message contained file descriptor"),
2204                                 &synthetic_reply);
2205                 if (r < 0)
2206                         return r;
2207
2208                 r = bus_seal_synthetic_message(bus, synthetic_reply);
2209                 if (r < 0)
2210                         return r;
2211
2212                 m = synthetic_reply;
2213         } else {
2214                 r = sd_bus_message_rewind(m, true);
2215                 if (r < 0)
2216                         return r;
2217         }
2218
2219         if (c->timeout != 0) {
2220                 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2221                 c->timeout = 0;
2222         }
2223
2224         bus->current_slot = sd_bus_slot_ref(slot);
2225         r = c->callback(bus, m, slot->userdata, &error_buffer);
2226         bus->current_slot = sd_bus_slot_unref(slot);
2227
2228         if (slot->floating) {
2229                 bus_slot_disconnect(slot);
2230                 sd_bus_slot_unref(slot);
2231         }
2232
2233         return bus_maybe_reply_error(m, r, &error_buffer);
2234 }
2235
2236 static int process_filter(sd_bus *bus, sd_bus_message *m) {
2237         _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2238         struct filter_callback *l;
2239         int r;
2240
2241         assert(bus);
2242         assert(m);
2243
2244         do {
2245                 bus->filter_callbacks_modified = false;
2246
2247                 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
2248                         sd_bus_slot *slot;
2249
2250                         if (bus->filter_callbacks_modified)
2251                                 break;
2252
2253                         /* Don't run this more than once per iteration */
2254                         if (l->last_iteration == bus->iteration_counter)
2255                                 continue;
2256
2257                         l->last_iteration = bus->iteration_counter;
2258
2259                         r = sd_bus_message_rewind(m, true);
2260                         if (r < 0)
2261                                 return r;
2262
2263                         slot = container_of(l, sd_bus_slot, filter_callback);
2264
2265                         bus->current_slot = sd_bus_slot_ref(slot);
2266                         r = l->callback(bus, m, slot->userdata, &error_buffer);
2267                         bus->current_slot = sd_bus_slot_unref(slot);
2268
2269                         r = bus_maybe_reply_error(m, r, &error_buffer);
2270                         if (r != 0)
2271                                 return r;
2272
2273                 }
2274
2275         } while (bus->filter_callbacks_modified);
2276
2277         return 0;
2278 }
2279
2280 static int process_match(sd_bus *bus, sd_bus_message *m) {
2281         int r;
2282
2283         assert(bus);
2284         assert(m);
2285
2286         do {
2287                 bus->match_callbacks_modified = false;
2288
2289                 r = bus_match_run(bus, &bus->match_callbacks, m);
2290                 if (r != 0)
2291                         return r;
2292
2293         } while (bus->match_callbacks_modified);
2294
2295         return 0;
2296 }
2297
2298 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
2299         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2300         int r;
2301
2302         assert(bus);
2303         assert(m);
2304
2305         if (bus->hello_flags & KDBUS_HELLO_MONITOR)
2306                 return 0;
2307
2308         if (bus->manual_peer_interface)
2309                 return 0;
2310
2311         if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2312                 return 0;
2313
2314         if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2315                 return 0;
2316
2317         if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2318                 return 1;
2319
2320         if (streq_ptr(m->member, "Ping"))
2321                 r = sd_bus_message_new_method_return(m, &reply);
2322         else if (streq_ptr(m->member, "GetMachineId")) {
2323                 sd_id128_t id;
2324                 char sid[33];
2325
2326                 r = sd_id128_get_machine(&id);
2327                 if (r < 0)
2328                         return r;
2329
2330                 r = sd_bus_message_new_method_return(m, &reply);
2331                 if (r < 0)
2332                         return r;
2333
2334                 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2335         } else {
2336                 r = sd_bus_message_new_method_errorf(
2337                                 m, &reply,
2338                                 SD_BUS_ERROR_UNKNOWN_METHOD,
2339                                  "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2340         }
2341
2342         if (r < 0)
2343                 return r;
2344
2345         r = sd_bus_send(bus, reply, NULL);
2346         if (r < 0)
2347                 return r;
2348
2349         return 1;
2350 }
2351
2352 static int process_fd_check(sd_bus *bus, sd_bus_message *m) {
2353         assert(bus);
2354         assert(m);
2355
2356         /* If we got a message with a file descriptor which we didn't
2357          * want to accept, then let's drop it. How can this even
2358          * happen? For example, when the kernel queues a message into
2359          * an activatable names's queue which allows fds, and then is
2360          * delivered to us later even though we ourselves did not
2361          * negotiate it. */
2362
2363         if (bus->hello_flags & KDBUS_HELLO_MONITOR)
2364                 return 0;
2365
2366         if (m->n_fds <= 0)
2367                 return 0;
2368
2369         if (bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)
2370                 return 0;
2371
2372         if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2373                 return 1; /* just eat it up */
2374
2375         return sd_bus_reply_method_errorf(m, SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Message contains file descriptors, which I cannot accept. Sorry.");
2376 }
2377
2378 static int process_message(sd_bus *bus, sd_bus_message *m) {
2379         int r;
2380
2381         assert(bus);
2382         assert(m);
2383
2384         bus->current_message = m;
2385         bus->iteration_counter++;
2386
2387         log_debug("Got message type=%s sender=%s destination=%s object=%s interface=%s member=%s cookie=%" PRIu64 " reply_cookie=%" PRIu64 " error=%s",
2388                   bus_message_type_to_string(m->header->type),
2389                   strna(sd_bus_message_get_sender(m)),
2390                   strna(sd_bus_message_get_destination(m)),
2391                   strna(sd_bus_message_get_path(m)),
2392                   strna(sd_bus_message_get_interface(m)),
2393                   strna(sd_bus_message_get_member(m)),
2394                   BUS_MESSAGE_COOKIE(m),
2395                   m->reply_cookie,
2396                   strna(m->error.message));
2397
2398         r = process_hello(bus, m);
2399         if (r != 0)
2400                 goto finish;
2401
2402         r = process_reply(bus, m);
2403         if (r != 0)
2404                 goto finish;
2405
2406         r = process_fd_check(bus, m);
2407         if (r != 0)
2408                 goto finish;
2409
2410         r = process_filter(bus, m);
2411         if (r != 0)
2412                 goto finish;
2413
2414         r = process_match(bus, m);
2415         if (r != 0)
2416                 goto finish;
2417
2418         r = process_builtin(bus, m);
2419         if (r != 0)
2420                 goto finish;
2421
2422         r = bus_process_object(bus, m);
2423
2424 finish:
2425         bus->current_message = NULL;
2426         return r;
2427 }
2428
2429 static int dispatch_track(sd_bus *bus) {
2430         assert(bus);
2431
2432         if (!bus->track_queue)
2433                 return 0;
2434
2435         bus_track_dispatch(bus->track_queue);
2436         return 1;
2437 }
2438
2439 static int process_running(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2440         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2441         int r;
2442
2443         assert(bus);
2444         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
2445
2446         r = process_timeout(bus);
2447         if (r != 0)
2448                 goto null_message;
2449
2450         r = dispatch_wqueue(bus);
2451         if (r != 0)
2452                 goto null_message;
2453
2454         r = dispatch_track(bus);
2455         if (r != 0)
2456                 goto null_message;
2457
2458         r = dispatch_rqueue(bus, hint_priority, priority, &m);
2459         if (r < 0)
2460                 return r;
2461         if (!m)
2462                 goto null_message;
2463
2464         r = process_message(bus, m);
2465         if (r != 0)
2466                 goto null_message;
2467
2468         if (ret) {
2469                 r = sd_bus_message_rewind(m, true);
2470                 if (r < 0)
2471                         return r;
2472
2473                 *ret = m;
2474                 m = NULL;
2475                 return 1;
2476         }
2477
2478         if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2479
2480                 log_debug("Unprocessed message call sender=%s object=%s interface=%s member=%s",
2481                           strna(sd_bus_message_get_sender(m)),
2482                           strna(sd_bus_message_get_path(m)),
2483                           strna(sd_bus_message_get_interface(m)),
2484                           strna(sd_bus_message_get_member(m)));
2485
2486                 r = sd_bus_reply_method_errorf(
2487                                 m,
2488                                 SD_BUS_ERROR_UNKNOWN_OBJECT,
2489                                 "Unknown object '%s'.", m->path);
2490                 if (r < 0)
2491                         return r;
2492         }
2493
2494         return 1;
2495
2496 null_message:
2497         if (r >= 0 && ret)
2498                 *ret = NULL;
2499
2500         return r;
2501 }
2502
2503 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2504         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2505         struct reply_callback *c;
2506         int r;
2507
2508         assert(bus);
2509         assert(bus->state == BUS_CLOSING);
2510
2511         c = hashmap_first(bus->reply_callbacks);
2512         if (c) {
2513                 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2514                 sd_bus_slot *slot;
2515
2516                 /* First, fail all outstanding method calls */
2517                 r = bus_message_new_synthetic_error(
2518                                 bus,
2519                                 c->cookie,
2520                                 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2521                                 &m);
2522                 if (r < 0)
2523                         return r;
2524
2525                 r = bus_seal_synthetic_message(bus, m);
2526                 if (r < 0)
2527                         return r;
2528
2529                 if (c->timeout != 0) {
2530                         prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2531                         c->timeout = 0;
2532                 }
2533
2534                 hashmap_remove(bus->reply_callbacks, &c->cookie);
2535                 c->cookie = 0;
2536
2537                 slot = container_of(c, sd_bus_slot, reply_callback);
2538
2539                 bus->iteration_counter++;
2540
2541                 bus->current_message = m;
2542                 bus->current_slot = sd_bus_slot_ref(slot);
2543                 r = c->callback(bus, m, slot->userdata, &error_buffer);
2544                 bus->current_slot = sd_bus_slot_unref(slot);
2545                 bus->current_message = NULL;
2546
2547                 if (slot->floating) {
2548                         bus_slot_disconnect(slot);
2549                         sd_bus_slot_unref(slot);
2550                 }
2551
2552                 return bus_maybe_reply_error(m, r, &error_buffer);
2553         }
2554
2555         /* Then, synthesize a Disconnected message */
2556         r = sd_bus_message_new_signal(
2557                         bus,
2558                         &m,
2559                         "/org/freedesktop/DBus/Local",
2560                         "org.freedesktop.DBus.Local",
2561                         "Disconnected");
2562         if (r < 0)
2563                 return r;
2564
2565         m->sender = "org.freedesktop.DBus.Local";
2566
2567         r = bus_seal_synthetic_message(bus, m);
2568         if (r < 0)
2569                 return r;
2570
2571         sd_bus_close(bus);
2572
2573         bus->current_message = m;
2574         bus->iteration_counter++;
2575
2576         r = process_filter(bus, m);
2577         if (r != 0)
2578                 goto finish;
2579
2580         r = process_match(bus, m);
2581         if (r != 0)
2582                 goto finish;
2583
2584         if (ret) {
2585                 *ret = m;
2586                 m = NULL;
2587         }
2588
2589         r = 1;
2590
2591 finish:
2592         bus->current_message = NULL;
2593
2594         return r;
2595 }
2596
2597 static int bus_process_internal(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2598         BUS_DONT_DESTROY(bus);
2599         int r;
2600
2601         /* Returns 0 when we didn't do anything. This should cause the
2602          * caller to invoke sd_bus_wait() before returning the next
2603          * time. Returns > 0 when we did something, which possibly
2604          * means *ret is filled in with an unprocessed message. */
2605
2606         assert_return(bus, -EINVAL);
2607         assert_return(!bus_pid_changed(bus), -ECHILD);
2608
2609         /* We don't allow recursively invoking sd_bus_process(). */
2610         assert_return(!bus->current_message, -EBUSY);
2611         assert(!bus->current_slot);
2612
2613         switch (bus->state) {
2614
2615         case BUS_UNSET:
2616                 return -ENOTCONN;
2617
2618         case BUS_CLOSED:
2619                 return -ECONNRESET;
2620
2621         case BUS_OPENING:
2622                 r = bus_socket_process_opening(bus);
2623                 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2624                         bus_enter_closing(bus);
2625                         r = 1;
2626                 } else if (r < 0)
2627                         return r;
2628                 if (ret)
2629                         *ret = NULL;
2630                 return r;
2631
2632         case BUS_AUTHENTICATING:
2633                 r = bus_socket_process_authenticating(bus);
2634                 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2635                         bus_enter_closing(bus);
2636                         r = 1;
2637                 } else if (r < 0)
2638                         return r;
2639
2640                 if (ret)
2641                         *ret = NULL;
2642
2643                 return r;
2644
2645         case BUS_RUNNING:
2646         case BUS_HELLO:
2647                 r = process_running(bus, hint_priority, priority, ret);
2648                 if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2649                         bus_enter_closing(bus);
2650                         r = 1;
2651
2652                         if (ret)
2653                                 *ret = NULL;
2654                 }
2655
2656                 return r;
2657
2658         case BUS_CLOSING:
2659                 return process_closing(bus, ret);
2660         }
2661
2662         assert_not_reached("Unknown state");
2663 }
2664
2665 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2666         return bus_process_internal(bus, false, 0, ret);
2667 }
2668
2669 _public_ int sd_bus_process_priority(sd_bus *bus, int64_t priority, sd_bus_message **ret) {
2670         return bus_process_internal(bus, true, priority, ret);
2671 }
2672
2673 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2674         struct pollfd p[2] = {};
2675         int r, e, n;
2676         struct timespec ts;
2677         usec_t m = (usec_t) -1;
2678
2679         assert(bus);
2680
2681         if (bus->state == BUS_CLOSING)
2682                 return 1;
2683
2684         if (!BUS_IS_OPEN(bus->state))
2685                 return -ENOTCONN;
2686
2687         e = sd_bus_get_events(bus);
2688         if (e < 0)
2689                 return e;
2690
2691         if (need_more)
2692                 /* The caller really needs some more data, he doesn't
2693                  * care about what's already read, or any timeouts
2694                  * except its own.*/
2695                 e |= POLLIN;
2696         else {
2697                 usec_t until;
2698                 /* The caller wants to process if there's something to
2699                  * process, but doesn't care otherwise */
2700
2701                 r = sd_bus_get_timeout(bus, &until);
2702                 if (r < 0)
2703                         return r;
2704                 if (r > 0) {
2705                         usec_t nw;
2706                         nw = now(CLOCK_MONOTONIC);
2707                         m = until > nw ? until - nw : 0;
2708                 }
2709         }
2710
2711         if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
2712                 m = timeout_usec;
2713
2714         p[0].fd = bus->input_fd;
2715         if (bus->output_fd == bus->input_fd) {
2716                 p[0].events = e;
2717                 n = 1;
2718         } else {
2719                 p[0].events = e & POLLIN;
2720                 p[1].fd = bus->output_fd;
2721                 p[1].events = e & POLLOUT;
2722                 n = 2;
2723         }
2724
2725         r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
2726         if (r < 0)
2727                 return -errno;
2728
2729         return r > 0 ? 1 : 0;
2730 }
2731
2732 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
2733
2734         assert_return(bus, -EINVAL);
2735         assert_return(!bus_pid_changed(bus), -ECHILD);
2736
2737         if (bus->state == BUS_CLOSING)
2738                 return 0;
2739
2740         if (!BUS_IS_OPEN(bus->state))
2741                 return -ENOTCONN;
2742
2743         if (bus->rqueue_size > 0)
2744                 return 0;
2745
2746         return bus_poll(bus, false, timeout_usec);
2747 }
2748
2749 _public_ int sd_bus_flush(sd_bus *bus) {
2750         int r;
2751
2752         assert_return(bus, -EINVAL);
2753         assert_return(!bus_pid_changed(bus), -ECHILD);
2754
2755         if (bus->state == BUS_CLOSING)
2756                 return 0;
2757
2758         if (!BUS_IS_OPEN(bus->state))
2759                 return -ENOTCONN;
2760
2761         r = bus_ensure_running(bus);
2762         if (r < 0)
2763                 return r;
2764
2765         if (bus->wqueue_size <= 0)
2766                 return 0;
2767
2768         for (;;) {
2769                 r = dispatch_wqueue(bus);
2770                 if (r < 0) {
2771                         if (r == -ENOTCONN || r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2772                                 bus_enter_closing(bus);
2773                                 return -ECONNRESET;
2774                         }
2775
2776                         return r;
2777                 }
2778
2779                 if (bus->wqueue_size <= 0)
2780                         return 0;
2781
2782                 r = bus_poll(bus, false, (uint64_t) -1);
2783                 if (r < 0)
2784                         return r;
2785         }
2786 }
2787
2788 _public_ int sd_bus_add_filter(
2789                 sd_bus *bus,
2790                 sd_bus_slot **slot,
2791                 sd_bus_message_handler_t callback,
2792                 void *userdata) {
2793
2794         sd_bus_slot *s;
2795
2796         assert_return(bus, -EINVAL);
2797         assert_return(callback, -EINVAL);
2798         assert_return(!bus_pid_changed(bus), -ECHILD);
2799
2800         s = bus_slot_allocate(bus, !slot, BUS_FILTER_CALLBACK, sizeof(struct filter_callback), userdata);
2801         if (!s)
2802                 return -ENOMEM;
2803
2804         s->filter_callback.callback = callback;
2805
2806         bus->filter_callbacks_modified = true;
2807         LIST_PREPEND(callbacks, bus->filter_callbacks, &s->filter_callback);
2808
2809         if (slot)
2810                 *slot = s;
2811
2812         return 0;
2813 }
2814
2815 _public_ int sd_bus_add_match(
2816                 sd_bus *bus,
2817                 sd_bus_slot **slot,
2818                 const char *match,
2819                 sd_bus_message_handler_t callback,
2820                 void *userdata) {
2821
2822         struct bus_match_component *components = NULL;
2823         unsigned n_components = 0;
2824         sd_bus_slot *s = NULL;
2825         int r = 0;
2826
2827         assert_return(bus, -EINVAL);
2828         assert_return(match, -EINVAL);
2829         assert_return(!bus_pid_changed(bus), -ECHILD);
2830
2831         r = bus_match_parse(match, &components, &n_components);
2832         if (r < 0)
2833                 goto finish;
2834
2835         s = bus_slot_allocate(bus, !slot, BUS_MATCH_CALLBACK, sizeof(struct match_callback), userdata);
2836         if (!s) {
2837                 r = -ENOMEM;
2838                 goto finish;
2839         }
2840
2841         s->match_callback.callback = callback;
2842         s->match_callback.cookie = ++bus->match_cookie;
2843
2844         if (bus->bus_client) {
2845
2846                 if (!bus->is_kernel) {
2847                         /* When this is not a kernel transport, we
2848                          * store the original match string, so that we
2849                          * can use it to remove the match again */
2850
2851                         s->match_callback.match_string = strdup(match);
2852                         if (!s->match_callback.match_string) {
2853                                 r = -ENOMEM;
2854                                 goto finish;
2855                         }
2856                 }
2857
2858                 r = bus_add_match_internal(bus, s->match_callback.match_string, components, n_components, s->match_callback.cookie);
2859                 if (r < 0)
2860                         goto finish;
2861         }
2862
2863         bus->match_callbacks_modified = true;
2864         r = bus_match_add(&bus->match_callbacks, components, n_components, &s->match_callback);
2865         if (r < 0)
2866                 goto finish;
2867
2868         if (slot)
2869                 *slot = s;
2870         s = NULL;
2871
2872 finish:
2873         bus_match_parse_free(components, n_components);
2874         sd_bus_slot_unref(s);
2875
2876         return r;
2877 }
2878
2879 int bus_remove_match_by_string(
2880                 sd_bus *bus,
2881                 const char *match,
2882                 sd_bus_message_handler_t callback,
2883                 void *userdata) {
2884
2885         struct bus_match_component *components = NULL;
2886         unsigned n_components = 0;
2887         struct match_callback *c;
2888         int r = 0;
2889
2890         assert_return(bus, -EINVAL);
2891         assert_return(match, -EINVAL);
2892         assert_return(!bus_pid_changed(bus), -ECHILD);
2893
2894         r = bus_match_parse(match, &components, &n_components);
2895         if (r < 0)
2896                 goto finish;
2897
2898         r = bus_match_find(&bus->match_callbacks, components, n_components, NULL, NULL, &c);
2899         if (r <= 0)
2900                 goto finish;
2901
2902         sd_bus_slot_unref(container_of(c, sd_bus_slot, match_callback));
2903
2904 finish:
2905         bus_match_parse_free(components, n_components);
2906
2907         return r;
2908 }
2909
2910 bool bus_pid_changed(sd_bus *bus) {
2911         assert(bus);
2912
2913         /* We don't support people creating a bus connection and
2914          * keeping it around over a fork(). Let's complain. */
2915
2916         return bus->original_pid != getpid();
2917 }
2918
2919 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2920         sd_bus *bus = userdata;
2921         int r;
2922
2923         assert(bus);
2924
2925         r = sd_bus_process(bus, NULL);
2926         if (r < 0)
2927                 return r;
2928
2929         return 1;
2930 }
2931
2932 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
2933         sd_bus *bus = userdata;
2934         int r;
2935
2936         assert(bus);
2937
2938         r = sd_bus_process(bus, NULL);
2939         if (r < 0)
2940                 return r;
2941
2942         return 1;
2943 }
2944
2945 static int prepare_callback(sd_event_source *s, void *userdata) {
2946         sd_bus *bus = userdata;
2947         int r, e;
2948         usec_t until;
2949
2950         assert(s);
2951         assert(bus);
2952
2953         e = sd_bus_get_events(bus);
2954         if (e < 0)
2955                 return e;
2956
2957         if (bus->output_fd != bus->input_fd) {
2958
2959                 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
2960                 if (r < 0)
2961                         return r;
2962
2963                 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
2964                 if (r < 0)
2965                         return r;
2966         } else {
2967                 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
2968                 if (r < 0)
2969                         return r;
2970         }
2971
2972         r = sd_bus_get_timeout(bus, &until);
2973         if (r < 0)
2974                 return r;
2975         if (r > 0) {
2976                 int j;
2977
2978                 j = sd_event_source_set_time(bus->time_event_source, until);
2979                 if (j < 0)
2980                         return j;
2981         }
2982
2983         r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
2984         if (r < 0)
2985                 return r;
2986
2987         return 1;
2988 }
2989
2990 static int quit_callback(sd_event_source *event, void *userdata) {
2991         sd_bus *bus = userdata;
2992
2993         assert(event);
2994
2995         sd_bus_flush(bus);
2996
2997         return 1;
2998 }
2999
3000 static int attach_io_events(sd_bus *bus) {
3001         int r;
3002
3003         assert(bus);
3004
3005         if (bus->input_fd < 0)
3006                 return 0;
3007
3008         if (!bus->event)
3009                 return 0;
3010
3011         if (!bus->input_io_event_source) {
3012                 r = sd_event_add_io(bus->event, &bus->input_io_event_source, bus->input_fd, 0, io_callback, bus);
3013                 if (r < 0)
3014                         return r;
3015
3016                 r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
3017                 if (r < 0)
3018                         return r;
3019
3020                 r = sd_event_source_set_priority(bus->input_io_event_source, bus->event_priority);
3021         } else
3022                 r = sd_event_source_set_io_fd(bus->input_io_event_source, bus->input_fd);
3023
3024         if (r < 0)
3025                 return r;
3026
3027         if (bus->output_fd != bus->input_fd) {
3028                 assert(bus->output_fd >= 0);
3029
3030                 if (!bus->output_io_event_source) {
3031                         r = sd_event_add_io(bus->event, &bus->output_io_event_source, bus->output_fd, 0, io_callback, bus);
3032                         if (r < 0)
3033                                 return r;
3034
3035                         r = sd_event_source_set_priority(bus->output_io_event_source, bus->event_priority);
3036                 } else
3037                         r = sd_event_source_set_io_fd(bus->output_io_event_source, bus->output_fd);
3038
3039                 if (r < 0)
3040                         return r;
3041         }
3042
3043         return 0;
3044 }
3045
3046 static void detach_io_events(sd_bus *bus) {
3047         assert(bus);
3048
3049         if (bus->input_io_event_source) {
3050                 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
3051                 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
3052         }
3053
3054         if (bus->output_io_event_source) {
3055                 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
3056                 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
3057         }
3058 }
3059
3060 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
3061         int r;
3062
3063         assert_return(bus, -EINVAL);
3064         assert_return(!bus->event, -EBUSY);
3065
3066         assert(!bus->input_io_event_source);
3067         assert(!bus->output_io_event_source);
3068         assert(!bus->time_event_source);
3069
3070         if (event)
3071                 bus->event = sd_event_ref(event);
3072         else  {
3073                 r = sd_event_default(&bus->event);
3074                 if (r < 0)
3075                         return r;
3076         }
3077
3078         bus->event_priority = priority;
3079
3080         r = sd_event_add_time(bus->event, &bus->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, bus);
3081         if (r < 0)
3082                 goto fail;
3083
3084         r = sd_event_source_set_priority(bus->time_event_source, priority);
3085         if (r < 0)
3086                 goto fail;
3087
3088         r = sd_event_add_exit(bus->event, &bus->quit_event_source, quit_callback, bus);
3089         if (r < 0)
3090                 goto fail;
3091
3092         r = attach_io_events(bus);
3093         if (r < 0)
3094                 goto fail;
3095
3096         return 0;
3097
3098 fail:
3099         sd_bus_detach_event(bus);
3100         return r;
3101 }
3102
3103 _public_ int sd_bus_detach_event(sd_bus *bus) {
3104         assert_return(bus, -EINVAL);
3105
3106         if (!bus->event)
3107                 return 0;
3108
3109         detach_io_events(bus);
3110
3111         if (bus->time_event_source) {
3112                 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
3113                 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
3114         }
3115
3116         if (bus->quit_event_source) {
3117                 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
3118                 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
3119         }
3120
3121         bus->event = sd_event_unref(bus->event);
3122         return 1;
3123 }
3124
3125 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
3126         assert_return(bus, NULL);
3127
3128         return bus->event;
3129 }
3130
3131 _public_ sd_bus_message* sd_bus_get_current_message(sd_bus *bus) {
3132         assert_return(bus, NULL);
3133
3134         return bus->current_message;
3135 }
3136
3137 _public_ sd_bus_slot* sd_bus_get_current_slot(sd_bus *bus) {
3138         assert_return(bus, NULL);
3139
3140         return bus->current_slot;
3141 }
3142
3143 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
3144         sd_bus *b = NULL;
3145         int r;
3146
3147         assert(bus_open);
3148         assert(default_bus);
3149
3150         if (!ret)
3151                 return !!*default_bus;
3152
3153         if (*default_bus) {
3154                 *ret = sd_bus_ref(*default_bus);
3155                 return 0;
3156         }
3157
3158         r = bus_open(&b);
3159         if (r < 0)
3160                 return r;
3161
3162         b->default_bus_ptr = default_bus;
3163         b->tid = gettid();
3164         *default_bus = b;
3165
3166         *ret = b;
3167         return 1;
3168 }
3169
3170 _public_ int sd_bus_default_system(sd_bus **ret) {
3171         static thread_local sd_bus *default_system_bus = NULL;
3172
3173         return bus_default(sd_bus_open_system, &default_system_bus, ret);
3174 }
3175
3176 _public_ int sd_bus_default_user(sd_bus **ret) {
3177         static thread_local sd_bus *default_user_bus = NULL;
3178
3179         return bus_default(sd_bus_open_user, &default_user_bus, ret);
3180 }
3181
3182 _public_ int sd_bus_default(sd_bus **ret) {
3183
3184         const char *e;
3185
3186         /* Let's try our best to reuse another cached connection. If
3187          * the starter bus type is set, connect via our normal
3188          * connection logic, ignoring $DBUS_STARTER_ADDRESS, so that
3189          * we can share the connection with the user/system default
3190          * bus. */
3191
3192         e = secure_getenv("DBUS_STARTER_BUS_TYPE");
3193         if (e) {
3194                 if (streq(e, "system"))
3195                         return sd_bus_default_system(ret);
3196                 else if (STR_IN_SET(e, "user", "session"))
3197                         return sd_bus_default_user(ret);
3198         }
3199
3200         /* No type is specified, so we have not other option than to
3201          * use the starter address if it is set. */
3202
3203         e = secure_getenv("DBUS_STARTER_ADDRESS");
3204         if (e) {
3205                 static thread_local sd_bus *default_starter_bus = NULL;
3206
3207                 return bus_default(sd_bus_open, &default_starter_bus, ret);
3208         }
3209
3210         /* Finally, if nothing is set use the cached connection for
3211          * the right scope */
3212
3213         if (cg_pid_get_owner_uid(0, NULL) >= 0)
3214                 return sd_bus_default_user(ret);
3215         else
3216                 return sd_bus_default_system(ret);
3217 }
3218
3219 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
3220         assert_return(b, -EINVAL);
3221         assert_return(tid, -EINVAL);
3222         assert_return(!bus_pid_changed(b), -ECHILD);
3223
3224         if (b->tid != 0) {
3225                 *tid = b->tid;
3226                 return 0;
3227         }
3228
3229         if (b->event)
3230                 return sd_event_get_tid(b->event, tid);
3231
3232         return -ENXIO;
3233 }
3234
3235 _public_ int sd_bus_path_encode(const char *prefix, const char *external_id, char **ret_path) {
3236         _cleanup_free_ char *e = NULL;
3237         char *ret;
3238
3239         assert_return(object_path_is_valid(prefix), -EINVAL);
3240         assert_return(external_id, -EINVAL);
3241         assert_return(ret_path, -EINVAL);
3242
3243         e = bus_label_escape(external_id);
3244         if (!e)
3245                 return -ENOMEM;
3246
3247         ret = strjoin(prefix, "/", e, NULL);
3248         if (!ret)
3249                 return -ENOMEM;
3250
3251         *ret_path = ret;
3252         return 0;
3253 }
3254
3255 _public_ int sd_bus_path_decode(const char *path, const char *prefix, char **external_id) {
3256         const char *e;
3257         char *ret;
3258
3259         assert_return(object_path_is_valid(path), -EINVAL);
3260         assert_return(object_path_is_valid(prefix), -EINVAL);
3261         assert_return(external_id, -EINVAL);
3262
3263         e = object_path_startswith(path, prefix);
3264         if (!e) {
3265                 *external_id = NULL;
3266                 return 0;
3267         }
3268
3269         ret = bus_label_unescape(e);
3270         if (!ret)
3271                 return -ENOMEM;
3272
3273         *external_id = ret;
3274         return 1;
3275 }
3276
3277 _public_ int sd_bus_get_peer_creds(sd_bus *bus, uint64_t mask, sd_bus_creds **ret) {
3278         sd_bus_creds *c;
3279         pid_t pid = 0;
3280         int r;
3281
3282         assert_return(bus, -EINVAL);
3283         assert_return(mask <= _SD_BUS_CREDS_ALL, -ENOTSUP);
3284         assert_return(ret, -EINVAL);
3285         assert_return(!bus_pid_changed(bus), -ECHILD);
3286
3287         if (bus->is_kernel)
3288                 return -ENOTSUP;
3289
3290         if (!BUS_IS_OPEN(bus->state))
3291                 return -ENOTCONN;
3292
3293         if (!bus->ucred_valid && !isempty(bus->label))
3294                 return -ENODATA;
3295
3296         c = bus_creds_new();
3297         if (!c)
3298                 return -ENOMEM;
3299
3300         if (bus->ucred_valid) {
3301                 pid = c->pid = bus->ucred.pid;
3302                 c->uid = bus->ucred.uid;
3303                 c->gid = bus->ucred.gid;
3304
3305                 c->mask |= (SD_BUS_CREDS_UID | SD_BUS_CREDS_PID | SD_BUS_CREDS_GID) & mask;
3306         }
3307
3308         if (!isempty(bus->label) && (mask & SD_BUS_CREDS_SELINUX_CONTEXT)) {
3309                 c->label = strdup(bus->label);
3310                 if (!c->label) {
3311                         sd_bus_creds_unref(c);
3312                         return -ENOMEM;
3313                 }
3314
3315                 c->mask |= SD_BUS_CREDS_SELINUX_CONTEXT;
3316         }
3317
3318         r = bus_creds_add_more(c, mask, pid, 0);
3319         if (r < 0)
3320                 return r;
3321
3322         *ret = c;
3323         return 0;
3324 }
3325
3326 _public_ int sd_bus_try_close(sd_bus *bus) {
3327         int r;
3328
3329         assert_return(bus, -EINVAL);
3330         assert_return(!bus_pid_changed(bus), -ECHILD);
3331
3332         if (!bus->is_kernel)
3333                 return -ENOTSUP;
3334
3335         if (!BUS_IS_OPEN(bus->state))
3336                 return -ENOTCONN;
3337
3338         if (bus->rqueue_size > 0)
3339                 return -EBUSY;
3340
3341         if (bus->wqueue_size > 0)
3342                 return -EBUSY;
3343
3344         r = bus_kernel_try_close(bus);
3345         if (r < 0)
3346                 return r;
3347
3348         sd_bus_close(bus);
3349         return 0;
3350 }
3351
3352 _public_ int sd_bus_get_name(sd_bus *bus, const char **name) {
3353         assert_return(bus, -EINVAL);
3354         assert_return(name, -EINVAL);
3355         assert_return(!bus_pid_changed(bus), -ECHILD);
3356
3357         *name = bus->connection_name;
3358         return 0;
3359 }