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