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