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