chiark / gitweb /
sd-bus: propagate handling errors for Hello method reply directly
[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         bool is_hello;
2078         usec_t n;
2079         int r;
2080
2081         assert(bus);
2082
2083         c = prioq_peek(bus->reply_callbacks_prioq);
2084         if (!c)
2085                 return 0;
2086
2087         n = now(CLOCK_MONOTONIC);
2088         if (c->timeout > n)
2089                 return 0;
2090
2091         r = bus_message_new_synthetic_error(
2092                         bus,
2093                         c->cookie,
2094                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
2095                         &m);
2096         if (r < 0)
2097                 return r;
2098
2099         r = bus_seal_synthetic_message(bus, m);
2100         if (r < 0)
2101                 return r;
2102
2103         assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
2104         c->timeout = 0;
2105
2106         ordered_hashmap_remove(bus->reply_callbacks, &c->cookie);
2107         c->cookie = 0;
2108
2109         slot = container_of(c, sd_bus_slot, reply_callback);
2110
2111         bus->iteration_counter++;
2112
2113         is_hello = bus->state == BUS_HELLO && c->callback == hello_callback;
2114
2115         bus->current_message = m;
2116         bus->current_slot = sd_bus_slot_ref(slot);
2117         bus->current_handler = c->callback;
2118         bus->current_userdata = slot->userdata;
2119         r = c->callback(m, slot->userdata, &error_buffer);
2120         bus->current_userdata = NULL;
2121         bus->current_handler = NULL;
2122         bus->current_slot = NULL;
2123         bus->current_message = NULL;
2124
2125         if (slot->floating) {
2126                 bus_slot_disconnect(slot);
2127                 sd_bus_slot_unref(slot);
2128         }
2129
2130         sd_bus_slot_unref(slot);
2131
2132         /* When this is the hello message and it failed, then make sure to propagate the error up, don't just log and
2133          * ignore the callback handler's return value. */
2134         if (is_hello)
2135                 return r;
2136
2137         return bus_maybe_reply_error(m, r, &error_buffer);
2138 }
2139
2140 static int process_hello(sd_bus *bus, sd_bus_message *m) {
2141         assert(bus);
2142         assert(m);
2143
2144         if (bus->state != BUS_HELLO)
2145                 return 0;
2146
2147         /* Let's make sure the first message on the bus is the HELLO
2148          * reply. But note that we don't actually parse the message
2149          * here (we leave that to the usual handling), we just verify
2150          * we don't let any earlier msg through. */
2151
2152         if (!IN_SET(m->header->type, SD_BUS_MESSAGE_METHOD_RETURN, SD_BUS_MESSAGE_METHOD_ERROR))
2153                 return -EIO;
2154
2155         if (m->reply_cookie != 1)
2156                 return -EIO;
2157
2158         return 0;
2159 }
2160
2161 static int process_reply(sd_bus *bus, sd_bus_message *m) {
2162         _cleanup_(sd_bus_message_unrefp) sd_bus_message *synthetic_reply = NULL;
2163         _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2164         struct reply_callback *c;
2165         sd_bus_slot *slot;
2166         bool is_hello;
2167         int r;
2168
2169         assert(bus);
2170         assert(m);
2171
2172         if (!IN_SET(m->header->type, SD_BUS_MESSAGE_METHOD_RETURN, SD_BUS_MESSAGE_METHOD_ERROR))
2173                 return 0;
2174
2175         if (m->destination && bus->unique_name && !streq_ptr(m->destination, bus->unique_name))
2176                 return 0;
2177
2178         c = ordered_hashmap_remove(bus->reply_callbacks, &m->reply_cookie);
2179         if (!c)
2180                 return 0;
2181
2182         c->cookie = 0;
2183
2184         slot = container_of(c, sd_bus_slot, reply_callback);
2185
2186         if (m->n_fds > 0 && !(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)) {
2187
2188                 /* If the reply contained a file descriptor which we
2189                  * didn't want we pass an error instead. */
2190
2191                 r = bus_message_new_synthetic_error(
2192                                 bus,
2193                                 m->reply_cookie,
2194                                 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Reply message contained file descriptor"),
2195                                 &synthetic_reply);
2196                 if (r < 0)
2197                         return r;
2198
2199                 /* Copy over original timestamp */
2200                 synthetic_reply->realtime = m->realtime;
2201                 synthetic_reply->monotonic = m->monotonic;
2202                 synthetic_reply->seqnum = m->seqnum;
2203
2204                 r = bus_seal_synthetic_message(bus, synthetic_reply);
2205                 if (r < 0)
2206                         return r;
2207
2208                 m = synthetic_reply;
2209         } else {
2210                 r = sd_bus_message_rewind(m, true);
2211                 if (r < 0)
2212                         return r;
2213         }
2214
2215         if (c->timeout != 0) {
2216                 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2217                 c->timeout = 0;
2218         }
2219
2220         is_hello = bus->state == BUS_HELLO && c->callback == hello_callback;
2221
2222         bus->current_slot = sd_bus_slot_ref(slot);
2223         bus->current_handler = c->callback;
2224         bus->current_userdata = slot->userdata;
2225         r = c->callback(m, slot->userdata, &error_buffer);
2226         bus->current_userdata = NULL;
2227         bus->current_handler = NULL;
2228         bus->current_slot = NULL;
2229
2230         if (slot->floating) {
2231                 bus_slot_disconnect(slot);
2232                 sd_bus_slot_unref(slot);
2233         }
2234
2235         sd_bus_slot_unref(slot);
2236
2237         /* When this is the hello message and it timed out, then make sure to propagate the error up, don't just log
2238          * and ignore the callback handler's return value. */
2239         if (is_hello)
2240                 return r;
2241
2242         return bus_maybe_reply_error(m, r, &error_buffer);
2243 }
2244
2245 static int process_filter(sd_bus *bus, sd_bus_message *m) {
2246         _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2247         struct filter_callback *l;
2248         int r;
2249
2250         assert(bus);
2251         assert(m);
2252
2253         do {
2254                 bus->filter_callbacks_modified = false;
2255
2256                 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
2257                         sd_bus_slot *slot;
2258
2259                         if (bus->filter_callbacks_modified)
2260                                 break;
2261
2262                         /* Don't run this more than once per iteration */
2263                         if (l->last_iteration == bus->iteration_counter)
2264                                 continue;
2265
2266                         l->last_iteration = bus->iteration_counter;
2267
2268                         r = sd_bus_message_rewind(m, true);
2269                         if (r < 0)
2270                                 return r;
2271
2272                         slot = container_of(l, sd_bus_slot, filter_callback);
2273
2274                         bus->current_slot = sd_bus_slot_ref(slot);
2275                         bus->current_handler = l->callback;
2276                         bus->current_userdata = slot->userdata;
2277                         r = l->callback(m, slot->userdata, &error_buffer);
2278                         bus->current_userdata = NULL;
2279                         bus->current_handler = NULL;
2280                         bus->current_slot = sd_bus_slot_unref(slot);
2281
2282                         r = bus_maybe_reply_error(m, r, &error_buffer);
2283                         if (r != 0)
2284                                 return r;
2285
2286                 }
2287
2288         } while (bus->filter_callbacks_modified);
2289
2290         return 0;
2291 }
2292
2293 static int process_match(sd_bus *bus, sd_bus_message *m) {
2294         int r;
2295
2296         assert(bus);
2297         assert(m);
2298
2299         do {
2300                 bus->match_callbacks_modified = false;
2301
2302                 r = bus_match_run(bus, &bus->match_callbacks, m);
2303                 if (r != 0)
2304                         return r;
2305
2306         } while (bus->match_callbacks_modified);
2307
2308         return 0;
2309 }
2310
2311 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
2312         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2313         int r;
2314
2315         assert(bus);
2316         assert(m);
2317
2318         if (bus->hello_flags & KDBUS_HELLO_MONITOR)
2319                 return 0;
2320
2321         if (bus->manual_peer_interface)
2322                 return 0;
2323
2324         if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2325                 return 0;
2326
2327         if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2328                 return 0;
2329
2330         if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2331                 return 1;
2332
2333         if (streq_ptr(m->member, "Ping"))
2334                 r = sd_bus_message_new_method_return(m, &reply);
2335         else if (streq_ptr(m->member, "GetMachineId")) {
2336                 sd_id128_t id;
2337                 char sid[33];
2338
2339                 r = sd_id128_get_machine(&id);
2340                 if (r < 0)
2341                         return r;
2342
2343                 r = sd_bus_message_new_method_return(m, &reply);
2344                 if (r < 0)
2345                         return r;
2346
2347                 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2348         } else {
2349                 r = sd_bus_message_new_method_errorf(
2350                                 m, &reply,
2351                                 SD_BUS_ERROR_UNKNOWN_METHOD,
2352                                  "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2353         }
2354
2355         if (r < 0)
2356                 return r;
2357
2358         r = sd_bus_send(bus, reply, NULL);
2359         if (r < 0)
2360                 return r;
2361
2362         return 1;
2363 }
2364
2365 static int process_fd_check(sd_bus *bus, sd_bus_message *m) {
2366         assert(bus);
2367         assert(m);
2368
2369         /* If we got a message with a file descriptor which we didn't
2370          * want to accept, then let's drop it. How can this even
2371          * happen? For example, when the kernel queues a message into
2372          * an activatable names's queue which allows fds, and then is
2373          * delivered to us later even though we ourselves did not
2374          * negotiate it. */
2375
2376         if (bus->hello_flags & KDBUS_HELLO_MONITOR)
2377                 return 0;
2378
2379         if (m->n_fds <= 0)
2380                 return 0;
2381
2382         if (bus->hello_flags & KDBUS_HELLO_ACCEPT_FD)
2383                 return 0;
2384
2385         if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2386                 return 1; /* just eat it up */
2387
2388         return sd_bus_reply_method_errorf(m, SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Message contains file descriptors, which I cannot accept. Sorry.");
2389 }
2390
2391 static int process_message(sd_bus *bus, sd_bus_message *m) {
2392         int r;
2393
2394         assert(bus);
2395         assert(m);
2396
2397         bus->current_message = m;
2398         bus->iteration_counter++;
2399
2400         log_debug_bus_message(m);
2401
2402         r = process_hello(bus, m);
2403         if (r != 0)
2404                 goto finish;
2405
2406         r = process_reply(bus, m);
2407         if (r != 0)
2408                 goto finish;
2409
2410         r = process_fd_check(bus, m);
2411         if (r != 0)
2412                 goto finish;
2413
2414         r = process_filter(bus, m);
2415         if (r != 0)
2416                 goto finish;
2417
2418         r = process_match(bus, m);
2419         if (r != 0)
2420                 goto finish;
2421
2422         r = process_builtin(bus, m);
2423         if (r != 0)
2424                 goto finish;
2425
2426         r = bus_process_object(bus, m);
2427
2428 finish:
2429         bus->current_message = NULL;
2430         return r;
2431 }
2432
2433 static int dispatch_track(sd_bus *bus) {
2434         assert(bus);
2435
2436         if (!bus->track_queue)
2437                 return 0;
2438
2439         bus_track_dispatch(bus->track_queue);
2440         return 1;
2441 }
2442
2443 static int process_running(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2444         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2445         int r;
2446
2447         assert(bus);
2448         assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
2449
2450         r = process_timeout(bus);
2451         if (r != 0)
2452                 goto null_message;
2453
2454         r = dispatch_wqueue(bus);
2455         if (r != 0)
2456                 goto null_message;
2457
2458         r = dispatch_track(bus);
2459         if (r != 0)
2460                 goto null_message;
2461
2462         r = dispatch_rqueue(bus, hint_priority, priority, &m);
2463         if (r < 0)
2464                 return r;
2465         if (!m)
2466                 goto null_message;
2467
2468         r = process_message(bus, m);
2469         if (r != 0)
2470                 goto null_message;
2471
2472         if (ret) {
2473                 r = sd_bus_message_rewind(m, true);
2474                 if (r < 0)
2475                         return r;
2476
2477                 *ret = m;
2478                 m = NULL;
2479                 return 1;
2480         }
2481
2482         if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2483
2484                 log_debug("Unprocessed message call sender=%s object=%s interface=%s member=%s",
2485                           strna(sd_bus_message_get_sender(m)),
2486                           strna(sd_bus_message_get_path(m)),
2487                           strna(sd_bus_message_get_interface(m)),
2488                           strna(sd_bus_message_get_member(m)));
2489
2490                 r = sd_bus_reply_method_errorf(
2491                                 m,
2492                                 SD_BUS_ERROR_UNKNOWN_OBJECT,
2493                                 "Unknown object '%s'.", m->path);
2494                 if (r < 0)
2495                         return r;
2496         }
2497
2498         return 1;
2499
2500 null_message:
2501         if (r >= 0 && ret)
2502                 *ret = NULL;
2503
2504         return r;
2505 }
2506
2507 static int bus_exit_now(sd_bus *bus) {
2508         assert(bus);
2509
2510         /* Exit due to close, if this is requested. If this is bus object is attached to an event source, invokes
2511          * sd_event_exit(), otherwise invokes libc exit(). */
2512
2513         if (bus->exited) /* did we already exit? */
2514                 return 0;
2515         if (!bus->exit_triggered) /* was the exit condition triggered? */
2516                 return 0;
2517         if (!bus->exit_on_disconnect) /* Shall we actually exit on disconnection? */
2518                 return 0;
2519
2520         bus->exited = true; /* never exit more than once */
2521
2522         log_debug("Bus connection disconnected, exiting.");
2523
2524         if (bus->event)
2525                 return sd_event_exit(bus->event, EXIT_FAILURE);
2526         else
2527                 exit(EXIT_FAILURE);
2528
2529         assert_not_reached("exit() didn't exit?");
2530 }
2531
2532 static int process_closing_reply_callback(sd_bus *bus, struct reply_callback *c) {
2533         _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2534         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2535         sd_bus_slot *slot;
2536         int r;
2537
2538         assert(bus);
2539         assert(c);
2540
2541         r = bus_message_new_synthetic_error(
2542                         bus,
2543                         c->cookie,
2544                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2545                         &m);
2546         if (r < 0)
2547                 return r;
2548
2549         r = bus_seal_synthetic_message(bus, m);
2550         if (r < 0)
2551                 return r;
2552
2553         if (c->timeout != 0) {
2554                 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2555                 c->timeout = 0;
2556         }
2557
2558         ordered_hashmap_remove(bus->reply_callbacks, &c->cookie);
2559         c->cookie = 0;
2560
2561         slot = container_of(c, sd_bus_slot, reply_callback);
2562
2563         bus->iteration_counter++;
2564
2565         bus->current_message = m;
2566         bus->current_slot = sd_bus_slot_ref(slot);
2567         bus->current_handler = c->callback;
2568         bus->current_userdata = slot->userdata;
2569         r = c->callback(m, slot->userdata, &error_buffer);
2570         bus->current_userdata = NULL;
2571         bus->current_handler = NULL;
2572         bus->current_slot = NULL;
2573         bus->current_message = NULL;
2574
2575         if (slot->floating) {
2576                 bus_slot_disconnect(slot);
2577                 sd_bus_slot_unref(slot);
2578         }
2579
2580         sd_bus_slot_unref(slot);
2581
2582         return bus_maybe_reply_error(m, r, &error_buffer);
2583 }
2584
2585 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2586         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2587         struct reply_callback *c;
2588         int r;
2589
2590         assert(bus);
2591         assert(bus->state == BUS_CLOSING);
2592
2593         /* First, fail all outstanding method calls */
2594         c = ordered_hashmap_first(bus->reply_callbacks);
2595         if (c)
2596                 return process_closing_reply_callback(bus, c);
2597
2598         /* Then, fake-drop all remaining bus tracking references */
2599         if (bus->tracks) {
2600                 bus_track_close(bus->tracks);
2601                 return 1;
2602         }
2603
2604         /* Then, synthesize a Disconnected message */
2605         r = sd_bus_message_new_signal(
2606                         bus,
2607                         &m,
2608                         "/org/freedesktop/DBus/Local",
2609                         "org.freedesktop.DBus.Local",
2610                         "Disconnected");
2611         if (r < 0)
2612                 return r;
2613
2614         bus_message_set_sender_local(bus, m);
2615
2616         r = bus_seal_synthetic_message(bus, m);
2617         if (r < 0)
2618                 return r;
2619
2620         sd_bus_close(bus);
2621
2622         bus->current_message = m;
2623         bus->iteration_counter++;
2624
2625         r = process_filter(bus, m);
2626         if (r != 0)
2627                 goto finish;
2628
2629         r = process_match(bus, m);
2630         if (r != 0)
2631                 goto finish;
2632
2633         /* Nothing else to do, exit now, if the condition holds */
2634         bus->exit_triggered = true;
2635         (void) bus_exit_now(bus);
2636
2637         if (ret) {
2638                 *ret = m;
2639                 m = NULL;
2640         }
2641
2642         r = 1;
2643
2644 finish:
2645         bus->current_message = NULL;
2646
2647         return r;
2648 }
2649
2650 static int bus_process_internal(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2651         BUS_DONT_DESTROY(bus);
2652         int r;
2653
2654         /* Returns 0 when we didn't do anything. This should cause the
2655          * caller to invoke sd_bus_wait() before returning the next
2656          * time. Returns > 0 when we did something, which possibly
2657          * means *ret is filled in with an unprocessed message. */
2658
2659         assert_return(bus, -EINVAL);
2660         assert_return(!bus_pid_changed(bus), -ECHILD);
2661
2662         /* We don't allow recursively invoking sd_bus_process(). */
2663         assert_return(!bus->current_message, -EBUSY);
2664         assert(!bus->current_slot);
2665
2666         switch (bus->state) {
2667
2668         case BUS_UNSET:
2669                 return -ENOTCONN;
2670
2671         case BUS_CLOSED:
2672                 return -ECONNRESET;
2673
2674         case BUS_OPENING:
2675                 r = bus_socket_process_opening(bus);
2676                 if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
2677                         bus_enter_closing(bus);
2678                         r = 1;
2679                 } else if (r < 0)
2680                         return r;
2681                 if (ret)
2682                         *ret = NULL;
2683                 return r;
2684
2685         case BUS_AUTHENTICATING:
2686                 r = bus_socket_process_authenticating(bus);
2687                 if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
2688                         bus_enter_closing(bus);
2689                         r = 1;
2690                 } else if (r < 0)
2691                         return r;
2692
2693                 if (ret)
2694                         *ret = NULL;
2695
2696                 return r;
2697
2698         case BUS_RUNNING:
2699         case BUS_HELLO:
2700                 r = process_running(bus, hint_priority, priority, ret);
2701                 if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
2702                         bus_enter_closing(bus);
2703                         r = 1;
2704
2705                         if (ret)
2706                                 *ret = NULL;
2707                 }
2708
2709                 return r;
2710
2711         case BUS_CLOSING:
2712                 return process_closing(bus, ret);
2713         }
2714
2715         assert_not_reached("Unknown state");
2716 }
2717
2718 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2719         return bus_process_internal(bus, false, 0, ret);
2720 }
2721
2722 _public_ int sd_bus_process_priority(sd_bus *bus, int64_t priority, sd_bus_message **ret) {
2723         return bus_process_internal(bus, true, priority, ret);
2724 }
2725
2726 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2727         struct pollfd p[2] = {};
2728         int r, e, n;
2729         struct timespec ts;
2730         usec_t m = USEC_INFINITY;
2731
2732         assert(bus);
2733
2734         if (bus->state == BUS_CLOSING)
2735                 return 1;
2736
2737         if (!BUS_IS_OPEN(bus->state))
2738                 return -ENOTCONN;
2739
2740         e = sd_bus_get_events(bus);
2741         if (e < 0)
2742                 return e;
2743
2744         if (need_more)
2745                 /* The caller really needs some more data, he doesn't
2746                  * care about what's already read, or any timeouts
2747                  * except its own. */
2748                 e |= POLLIN;
2749         else {
2750                 usec_t until;
2751                 /* The caller wants to process if there's something to
2752                  * process, but doesn't care otherwise */
2753
2754                 r = sd_bus_get_timeout(bus, &until);
2755                 if (r < 0)
2756                         return r;
2757                 if (r > 0) {
2758                         usec_t nw;
2759                         nw = now(CLOCK_MONOTONIC);
2760                         m = until > nw ? until - nw : 0;
2761                 }
2762         }
2763
2764         if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
2765                 m = timeout_usec;
2766
2767         p[0].fd = bus->input_fd;
2768         if (bus->output_fd == bus->input_fd) {
2769                 p[0].events = e;
2770                 n = 1;
2771         } else {
2772                 p[0].events = e & POLLIN;
2773                 p[1].fd = bus->output_fd;
2774                 p[1].events = e & POLLOUT;
2775                 n = 2;
2776         }
2777
2778         r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
2779         if (r < 0)
2780                 return -errno;
2781
2782         return r > 0 ? 1 : 0;
2783 }
2784
2785 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
2786
2787         assert_return(bus, -EINVAL);
2788         assert_return(!bus_pid_changed(bus), -ECHILD);
2789
2790         if (bus->state == BUS_CLOSING)
2791                 return 0;
2792
2793         if (!BUS_IS_OPEN(bus->state))
2794                 return -ENOTCONN;
2795
2796         if (bus->rqueue_size > 0)
2797                 return 0;
2798
2799         return bus_poll(bus, false, timeout_usec);
2800 }
2801
2802 _public_ int sd_bus_flush(sd_bus *bus) {
2803         int r;
2804
2805         assert_return(bus, -EINVAL);
2806         assert_return(!bus_pid_changed(bus), -ECHILD);
2807
2808         if (bus->state == BUS_CLOSING)
2809                 return 0;
2810
2811         if (!BUS_IS_OPEN(bus->state))
2812                 return -ENOTCONN;
2813
2814         r = bus_ensure_running(bus);
2815         if (r < 0)
2816                 return r;
2817
2818         if (bus->wqueue_size <= 0)
2819                 return 0;
2820
2821         for (;;) {
2822                 r = dispatch_wqueue(bus);
2823                 if (r < 0) {
2824                         if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
2825                                 bus_enter_closing(bus);
2826                                 return -ECONNRESET;
2827                         }
2828
2829                         return r;
2830                 }
2831
2832                 if (bus->wqueue_size <= 0)
2833                         return 0;
2834
2835                 r = bus_poll(bus, false, (uint64_t) -1);
2836                 if (r < 0)
2837                         return r;
2838         }
2839 }
2840
2841 _public_ int sd_bus_add_filter(
2842                 sd_bus *bus,
2843                 sd_bus_slot **slot,
2844                 sd_bus_message_handler_t callback,
2845                 void *userdata) {
2846
2847         sd_bus_slot *s;
2848
2849         assert_return(bus, -EINVAL);
2850         assert_return(callback, -EINVAL);
2851         assert_return(!bus_pid_changed(bus), -ECHILD);
2852
2853         s = bus_slot_allocate(bus, !slot, BUS_FILTER_CALLBACK, sizeof(struct filter_callback), userdata);
2854         if (!s)
2855                 return -ENOMEM;
2856
2857         s->filter_callback.callback = callback;
2858
2859         bus->filter_callbacks_modified = true;
2860         LIST_PREPEND(callbacks, bus->filter_callbacks, &s->filter_callback);
2861
2862         if (slot)
2863                 *slot = s;
2864
2865         return 0;
2866 }
2867
2868 _public_ int sd_bus_add_match(
2869                 sd_bus *bus,
2870                 sd_bus_slot **slot,
2871                 const char *match,
2872                 sd_bus_message_handler_t callback,
2873                 void *userdata) {
2874
2875         struct bus_match_component *components = NULL;
2876         unsigned n_components = 0;
2877         sd_bus_slot *s = NULL;
2878         int r = 0;
2879
2880         assert_return(bus, -EINVAL);
2881         assert_return(match, -EINVAL);
2882         assert_return(!bus_pid_changed(bus), -ECHILD);
2883
2884         r = bus_match_parse(match, &components, &n_components);
2885         if (r < 0)
2886                 goto finish;
2887
2888         s = bus_slot_allocate(bus, !slot, BUS_MATCH_CALLBACK, sizeof(struct match_callback), userdata);
2889         if (!s) {
2890                 r = -ENOMEM;
2891                 goto finish;
2892         }
2893
2894         s->match_callback.callback = callback;
2895
2896         if (bus->bus_client) {
2897                 enum bus_match_scope scope;
2898
2899                 scope = bus_match_get_scope(components, n_components);
2900
2901                 /* Do not install server-side matches for matches
2902                  * against the local service, interface or bus path. */
2903                 if (scope != BUS_MATCH_LOCAL) {
2904
2905                         /* We store the original match string, so that
2906                          * we can use it to remove the match again. */
2907
2908                         s->match_callback.match_string = strdup(match);
2909                         if (!s->match_callback.match_string) {
2910                                 r = -ENOMEM;
2911                                 goto finish;
2912                         }
2913
2914                         r = bus_add_match_internal(bus, s->match_callback.match_string, components, n_components);
2915                         if (r < 0)
2916                                 goto finish;
2917
2918                         s->match_added = true;
2919                 }
2920         }
2921
2922         bus->match_callbacks_modified = true;
2923         r = bus_match_add(&bus->match_callbacks, components, n_components, &s->match_callback);
2924         if (r < 0)
2925                 goto finish;
2926
2927         if (slot)
2928                 *slot = s;
2929         s = NULL;
2930
2931 finish:
2932         bus_match_parse_free(components, n_components);
2933         sd_bus_slot_unref(s);
2934
2935         return r;
2936 }
2937
2938 #if 0 /// UNNEEDED by elogind
2939 int bus_remove_match_by_string(
2940                 sd_bus *bus,
2941                 const char *match,
2942                 sd_bus_message_handler_t callback,
2943                 void *userdata) {
2944
2945         struct bus_match_component *components = NULL;
2946         unsigned n_components = 0;
2947         struct match_callback *c;
2948         int r = 0;
2949
2950         assert_return(bus, -EINVAL);
2951         assert_return(match, -EINVAL);
2952         assert_return(!bus_pid_changed(bus), -ECHILD);
2953
2954         r = bus_match_parse(match, &components, &n_components);
2955         if (r < 0)
2956                 goto finish;
2957
2958         r = bus_match_find(&bus->match_callbacks, components, n_components, NULL, NULL, &c);
2959         if (r <= 0)
2960                 goto finish;
2961
2962         sd_bus_slot_unref(container_of(c, sd_bus_slot, match_callback));
2963
2964 finish:
2965         bus_match_parse_free(components, n_components);
2966
2967         return r;
2968 }
2969 #endif // 0
2970
2971 bool bus_pid_changed(sd_bus *bus) {
2972         assert(bus);
2973
2974         /* We don't support people creating a bus connection and
2975          * keeping it around over a fork(). Let's complain. */
2976
2977         return bus->original_pid != getpid_cached();
2978 }
2979
2980 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2981         sd_bus *bus = userdata;
2982         int r;
2983
2984         assert(bus);
2985
2986         r = sd_bus_process(bus, NULL);
2987         if (r < 0)
2988                 return r;
2989
2990         return 1;
2991 }
2992
2993 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
2994         sd_bus *bus = userdata;
2995         int r;
2996
2997         assert(bus);
2998
2999         r = sd_bus_process(bus, NULL);
3000         if (r < 0)
3001                 return r;
3002
3003         return 1;
3004 }
3005
3006 static int prepare_callback(sd_event_source *s, void *userdata) {
3007         sd_bus *bus = userdata;
3008         int r, e;
3009         usec_t until;
3010
3011         assert(s);
3012         assert(bus);
3013
3014         e = sd_bus_get_events(bus);
3015         if (e < 0)
3016                 return e;
3017
3018         if (bus->output_fd != bus->input_fd) {
3019
3020                 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
3021                 if (r < 0)
3022                         return r;
3023
3024                 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
3025                 if (r < 0)
3026                         return r;
3027         } else {
3028                 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
3029                 if (r < 0)
3030                         return r;
3031         }
3032
3033         r = sd_bus_get_timeout(bus, &until);
3034         if (r < 0)
3035                 return r;
3036         if (r > 0) {
3037                 int j;
3038
3039                 j = sd_event_source_set_time(bus->time_event_source, until);
3040                 if (j < 0)
3041                         return j;
3042         }
3043
3044         r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
3045         if (r < 0)
3046                 return r;
3047
3048         return 1;
3049 }
3050
3051 static int quit_callback(sd_event_source *event, void *userdata) {
3052         sd_bus *bus = userdata;
3053
3054         assert(event);
3055
3056         sd_bus_flush(bus);
3057         sd_bus_close(bus);
3058
3059         return 1;
3060 }
3061
3062 static int attach_io_events(sd_bus *bus) {
3063         int r;
3064
3065         assert(bus);
3066
3067         if (bus->input_fd < 0)
3068                 return 0;
3069
3070         if (!bus->event)
3071                 return 0;
3072
3073         if (!bus->input_io_event_source) {
3074                 r = sd_event_add_io(bus->event, &bus->input_io_event_source, bus->input_fd, 0, io_callback, bus);
3075                 if (r < 0)
3076                         return r;
3077
3078                 r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
3079                 if (r < 0)
3080                         return r;
3081
3082                 r = sd_event_source_set_priority(bus->input_io_event_source, bus->event_priority);
3083                 if (r < 0)
3084                         return r;
3085
3086                 r = sd_event_source_set_description(bus->input_io_event_source, "bus-input");
3087         } else
3088                 r = sd_event_source_set_io_fd(bus->input_io_event_source, bus->input_fd);
3089
3090         if (r < 0)
3091                 return r;
3092
3093         if (bus->output_fd != bus->input_fd) {
3094                 assert(bus->output_fd >= 0);
3095
3096                 if (!bus->output_io_event_source) {
3097                         r = sd_event_add_io(bus->event, &bus->output_io_event_source, bus->output_fd, 0, io_callback, bus);
3098                         if (r < 0)
3099                                 return r;
3100
3101                         r = sd_event_source_set_priority(bus->output_io_event_source, bus->event_priority);
3102                         if (r < 0)
3103                                 return r;
3104
3105                         r = sd_event_source_set_description(bus->input_io_event_source, "bus-output");
3106                 } else
3107                         r = sd_event_source_set_io_fd(bus->output_io_event_source, bus->output_fd);
3108
3109                 if (r < 0)
3110                         return r;
3111         }
3112
3113         return 0;
3114 }
3115
3116 static void detach_io_events(sd_bus *bus) {
3117         assert(bus);
3118
3119         if (bus->input_io_event_source) {
3120                 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
3121                 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
3122         }
3123
3124         if (bus->output_io_event_source) {
3125                 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
3126                 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
3127         }
3128 }
3129
3130 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
3131         int r;
3132
3133         assert_return(bus, -EINVAL);
3134         assert_return(!bus->event, -EBUSY);
3135
3136         assert(!bus->input_io_event_source);
3137         assert(!bus->output_io_event_source);
3138         assert(!bus->time_event_source);
3139
3140         if (event)
3141                 bus->event = sd_event_ref(event);
3142         else  {
3143                 r = sd_event_default(&bus->event);
3144                 if (r < 0)
3145                         return r;
3146         }
3147
3148         bus->event_priority = priority;
3149
3150         r = sd_event_add_time(bus->event, &bus->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, bus);
3151         if (r < 0)
3152                 goto fail;
3153
3154         r = sd_event_source_set_priority(bus->time_event_source, priority);
3155         if (r < 0)
3156                 goto fail;
3157
3158         r = sd_event_source_set_description(bus->time_event_source, "bus-time");
3159         if (r < 0)
3160                 goto fail;
3161
3162         r = sd_event_add_exit(bus->event, &bus->quit_event_source, quit_callback, bus);
3163         if (r < 0)
3164                 goto fail;
3165
3166         r = sd_event_source_set_description(bus->quit_event_source, "bus-exit");
3167         if (r < 0)
3168                 goto fail;
3169
3170         r = attach_io_events(bus);
3171         if (r < 0)
3172                 goto fail;
3173
3174         return 0;
3175
3176 fail:
3177         sd_bus_detach_event(bus);
3178         return r;
3179 }
3180
3181 _public_ int sd_bus_detach_event(sd_bus *bus) {
3182         assert_return(bus, -EINVAL);
3183
3184         if (!bus->event)
3185                 return 0;
3186
3187         detach_io_events(bus);
3188
3189         if (bus->time_event_source) {
3190                 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
3191                 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
3192         }
3193
3194         if (bus->quit_event_source) {
3195                 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
3196                 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
3197         }
3198
3199         bus->event = sd_event_unref(bus->event);
3200         return 1;
3201 }
3202
3203 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
3204         assert_return(bus, NULL);
3205
3206         return bus->event;
3207 }
3208
3209 _public_ sd_bus_message* sd_bus_get_current_message(sd_bus *bus) {
3210         assert_return(bus, NULL);
3211
3212         return bus->current_message;
3213 }
3214
3215 _public_ sd_bus_slot* sd_bus_get_current_slot(sd_bus *bus) {
3216         assert_return(bus, NULL);
3217
3218         return bus->current_slot;
3219 }
3220
3221 _public_ sd_bus_message_handler_t sd_bus_get_current_handler(sd_bus *bus) {
3222         assert_return(bus, NULL);
3223
3224         return bus->current_handler;
3225 }
3226
3227 _public_ void* sd_bus_get_current_userdata(sd_bus *bus) {
3228         assert_return(bus, NULL);
3229
3230         return bus->current_userdata;
3231 }
3232
3233 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
3234         sd_bus *b = NULL;
3235         int r;
3236
3237         assert(bus_open);
3238         assert(default_bus);
3239
3240         if (!ret)
3241                 return !!*default_bus;
3242
3243         if (*default_bus) {
3244                 *ret = sd_bus_ref(*default_bus);
3245                 return 0;
3246         }
3247
3248         r = bus_open(&b);
3249         if (r < 0)
3250                 return r;
3251
3252         b->default_bus_ptr = default_bus;
3253         b->tid = gettid();
3254         *default_bus = b;
3255
3256         *ret = b;
3257         return 1;
3258 }
3259
3260 _public_ int sd_bus_default_system(sd_bus **ret) {
3261         return bus_default(sd_bus_open_system, &default_system_bus, ret);
3262 }
3263
3264
3265 _public_ int sd_bus_default_user(sd_bus **ret) {
3266 #if 0 /// elogind does not support user buses
3267         return bus_default(sd_bus_open_user, &default_user_bus, ret);
3268 #else
3269         return sd_bus_default_system(ret);
3270 #endif // 0
3271 }
3272
3273 _public_ int sd_bus_default(sd_bus **ret) {
3274
3275         const char *e;
3276
3277         /* Let's try our best to reuse another cached connection. If
3278          * the starter bus type is set, connect via our normal
3279          * connection logic, ignoring $DBUS_STARTER_ADDRESS, so that
3280          * we can share the connection with the user/system default
3281          * bus. */
3282
3283         e = secure_getenv("DBUS_STARTER_BUS_TYPE");
3284         if (e) {
3285                 if (streq(e, "system"))
3286                         return sd_bus_default_system(ret);
3287 #if 0 /// elogind does not support systemd units
3288                 else if (STR_IN_SET(e, "user", "session"))
3289                         return sd_bus_default_user(ret);
3290 #endif // 0
3291         }
3292
3293         /* No type is specified, so we have not other option than to
3294          * use the starter address if it is set. */
3295         e = secure_getenv("DBUS_STARTER_ADDRESS");
3296         if (e)
3297                 return bus_default(sd_bus_open, &default_starter_bus, ret);
3298
3299         /* Finally, if nothing is set use the cached connection for
3300          * the right scope */
3301
3302 #if 0 /// elogind does not support systemd user instances
3303         if (cg_pid_get_owner_uid(0, NULL) >= 0)
3304                 return sd_bus_default_user(ret);
3305         else
3306 #endif // 0
3307                 return sd_bus_default_system(ret);
3308 }
3309
3310 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
3311         assert_return(b, -EINVAL);
3312         assert_return(tid, -EINVAL);
3313         assert_return(!bus_pid_changed(b), -ECHILD);
3314
3315         if (b->tid != 0) {
3316                 *tid = b->tid;
3317                 return 0;
3318         }
3319
3320         if (b->event)
3321                 return sd_event_get_tid(b->event, tid);
3322
3323         return -ENXIO;
3324 }
3325
3326 _public_ int sd_bus_path_encode(const char *prefix, const char *external_id, char **ret_path) {
3327         _cleanup_free_ char *e = NULL;
3328         char *ret;
3329
3330         assert_return(object_path_is_valid(prefix), -EINVAL);
3331         assert_return(external_id, -EINVAL);
3332         assert_return(ret_path, -EINVAL);
3333
3334         e = bus_label_escape(external_id);
3335         if (!e)
3336                 return -ENOMEM;
3337
3338         ret = strjoin(prefix, "/", e);
3339         if (!ret)
3340                 return -ENOMEM;
3341
3342         *ret_path = ret;
3343         return 0;
3344 }
3345
3346 _public_ int sd_bus_path_decode(const char *path, const char *prefix, char **external_id) {
3347         const char *e;
3348         char *ret;
3349
3350         assert_return(object_path_is_valid(path), -EINVAL);
3351         assert_return(object_path_is_valid(prefix), -EINVAL);
3352         assert_return(external_id, -EINVAL);
3353
3354         e = object_path_startswith(path, prefix);
3355         if (!e) {
3356                 *external_id = NULL;
3357                 return 0;
3358         }
3359
3360         ret = bus_label_unescape(e);
3361         if (!ret)
3362                 return -ENOMEM;
3363
3364         *external_id = ret;
3365         return 1;
3366 }
3367
3368 _public_ int sd_bus_path_encode_many(char **out, const char *path_template, ...) {
3369         _cleanup_strv_free_ char **labels = NULL;
3370         char *path, *path_pos, **label_pos;
3371         const char *sep, *template_pos;
3372         size_t path_length;
3373         va_list list;
3374         int r;
3375
3376         assert_return(out, -EINVAL);
3377         assert_return(path_template, -EINVAL);
3378
3379         path_length = strlen(path_template);
3380
3381         va_start(list, path_template);
3382         for (sep = strchr(path_template, '%'); sep; sep = strchr(sep + 1, '%')) {
3383                 const char *arg;
3384                 char *label;
3385
3386                 arg = va_arg(list, const char *);
3387                 if (!arg) {
3388                         va_end(list);
3389                         return -EINVAL;
3390                 }
3391
3392                 label = bus_label_escape(arg);
3393                 if (!label) {
3394                         va_end(list);
3395                         return -ENOMEM;
3396                 }
3397
3398                 r = strv_consume(&labels, label);
3399                 if (r < 0) {
3400                         va_end(list);
3401                         return r;
3402                 }
3403
3404                 /* add label length, but account for the format character */
3405                 path_length += strlen(label) - 1;
3406         }
3407         va_end(list);
3408
3409         path = malloc(path_length + 1);
3410         if (!path)
3411                 return -ENOMEM;
3412
3413         path_pos = path;
3414         label_pos = labels;
3415
3416         for (template_pos = path_template; *template_pos; ) {
3417                 sep = strchrnul(template_pos, '%');
3418                 path_pos = mempcpy(path_pos, template_pos, sep - template_pos);
3419                 if (!*sep)
3420                         break;
3421
3422                 path_pos = stpcpy(path_pos, *label_pos++);
3423                 template_pos = sep + 1;
3424         }
3425
3426         *path_pos = 0;
3427         *out = path;
3428         return 0;
3429 }
3430
3431 _public_ int sd_bus_path_decode_many(const char *path, const char *path_template, ...) {
3432         _cleanup_strv_free_ char **labels = NULL;
3433         const char *template_pos, *path_pos;
3434         char **label_pos;
3435         va_list list;
3436         int r;
3437
3438         /*
3439          * This decodes an object-path based on a template argument. The
3440          * template consists of a verbatim path, optionally including special
3441          * directives:
3442          *
3443          *   - Each occurrence of '%' in the template matches an arbitrary
3444          *     substring of a label in the given path. At most one such
3445          *     directive is allowed per label. For each such directive, the
3446          *     caller must provide an output parameter (char **) via va_arg. If
3447          *     NULL is passed, the given label is verified, but not returned.
3448          *     For each matched label, the *decoded* label is stored in the
3449          *     passed output argument, and the caller is responsible to free
3450          *     it. Note that the output arguments are only modified if the
3451          *     actualy path matched the template. Otherwise, they're left
3452          *     untouched.
3453          *
3454          * This function returns <0 on error, 0 if the path does not match the
3455          * template, 1 if it matched.
3456          */
3457
3458         assert_return(path, -EINVAL);
3459         assert_return(path_template, -EINVAL);
3460
3461         path_pos = path;
3462
3463         for (template_pos = path_template; *template_pos; ) {
3464                 const char *sep;
3465                 size_t length;
3466                 char *label;
3467
3468                 /* verify everything until the next '%' matches verbatim */
3469                 sep = strchrnul(template_pos, '%');
3470                 length = sep - template_pos;
3471                 if (strncmp(path_pos, template_pos, length))
3472                         return 0;
3473
3474                 path_pos += length;
3475                 template_pos += length;
3476
3477                 if (!*template_pos)
3478                         break;
3479
3480                 /* We found the next '%' character. Everything up until here
3481                  * matched. We now skip ahead to the end of this label and make
3482                  * sure it matches the tail of the label in the path. Then we
3483                  * decode the string in-between and save it for later use. */
3484
3485                 ++template_pos; /* skip over '%' */
3486
3487                 sep = strchrnul(template_pos, '/');
3488                 length = sep - template_pos; /* length of suffix to match verbatim */
3489
3490                 /* verify the suffixes match */
3491                 sep = strchrnul(path_pos, '/');
3492                 if (sep - path_pos < (ssize_t)length ||
3493                     strncmp(sep - length, template_pos, length))
3494                         return 0;
3495
3496                 template_pos += length; /* skip over matched label */
3497                 length = sep - path_pos - length; /* length of sub-label to decode */
3498
3499                 /* store unescaped label for later use */
3500                 label = bus_label_unescape_n(path_pos, length);
3501                 if (!label)
3502                         return -ENOMEM;
3503
3504                 r = strv_consume(&labels, label);
3505                 if (r < 0)
3506                         return r;
3507
3508                 path_pos = sep; /* skip decoded label and suffix */
3509         }
3510
3511         /* end of template must match end of path */
3512         if (*path_pos)
3513                 return 0;
3514
3515         /* copy the labels over to the caller */
3516         va_start(list, path_template);
3517         for (label_pos = labels; label_pos && *label_pos; ++label_pos) {
3518                 char **arg;
3519
3520                 arg = va_arg(list, char **);
3521                 if (arg)
3522                         *arg = *label_pos;
3523                 else
3524                         free(*label_pos);
3525         }
3526         va_end(list);
3527
3528         labels = mfree(labels);
3529         return 1;
3530 }
3531
3532 _public_ int sd_bus_try_close(sd_bus *bus) {
3533         assert_return(bus, -EINVAL);
3534         assert_return(!bus_pid_changed(bus), -ECHILD);
3535
3536         return -EOPNOTSUPP;
3537 }
3538
3539 _public_ int sd_bus_get_description(sd_bus *bus, const char **description) {
3540         assert_return(bus, -EINVAL);
3541         assert_return(description, -EINVAL);
3542         assert_return(bus->description, -ENXIO);
3543         assert_return(!bus_pid_changed(bus), -ECHILD);
3544
3545         *description = bus->description;
3546         return 0;
3547 }
3548
3549 int bus_get_root_path(sd_bus *bus) {
3550         int r;
3551
3552         if (bus->cgroup_root)
3553                 return 0;
3554
3555         r = cg_get_root_path(&bus->cgroup_root);
3556         if (r == -ENOENT) {
3557                 bus->cgroup_root = strdup("/");
3558                 if (!bus->cgroup_root)
3559                         return -ENOMEM;
3560
3561                 r = 0;
3562         }
3563
3564         return r;
3565 }
3566
3567 _public_ int sd_bus_get_scope(sd_bus *bus, const char **scope) {
3568         assert_return(bus, -EINVAL);
3569         assert_return(scope, -EINVAL);
3570         assert_return(!bus_pid_changed(bus), -ECHILD);
3571
3572         if (bus->is_user) {
3573                 *scope = "user";
3574                 return 0;
3575         }
3576
3577         if (bus->is_system) {
3578                 *scope = "system";
3579                 return 0;
3580         }
3581
3582         return -ENODATA;
3583 }
3584
3585 _public_ int sd_bus_get_address(sd_bus *bus, const char **address) {
3586
3587         assert_return(bus, -EINVAL);
3588         assert_return(address, -EINVAL);
3589         assert_return(!bus_pid_changed(bus), -ECHILD);
3590
3591         if (bus->address) {
3592                 *address = bus->address;
3593                 return 0;
3594         }
3595
3596         return -ENODATA;
3597 }
3598
3599 _public_ int sd_bus_get_creds_mask(sd_bus *bus, uint64_t *mask) {
3600         assert_return(bus, -EINVAL);
3601         assert_return(mask, -EINVAL);
3602         assert_return(!bus_pid_changed(bus), -ECHILD);
3603
3604         *mask = bus->creds_mask;
3605         return 0;
3606 }
3607
3608 _public_ int sd_bus_is_bus_client(sd_bus *bus) {
3609         assert_return(bus, -EINVAL);
3610         assert_return(!bus_pid_changed(bus), -ECHILD);
3611
3612         return bus->bus_client;
3613 }
3614
3615 _public_ int sd_bus_is_server(sd_bus *bus) {
3616         assert_return(bus, -EINVAL);
3617         assert_return(!bus_pid_changed(bus), -ECHILD);
3618
3619         return bus->is_server;
3620 }
3621
3622 _public_ int sd_bus_is_anonymous(sd_bus *bus) {
3623         assert_return(bus, -EINVAL);
3624         assert_return(!bus_pid_changed(bus), -ECHILD);
3625
3626         return bus->anonymous_auth;
3627 }
3628
3629 _public_ int sd_bus_is_trusted(sd_bus *bus) {
3630         assert_return(bus, -EINVAL);
3631         assert_return(!bus_pid_changed(bus), -ECHILD);
3632
3633         return bus->trusted;
3634 }
3635
3636 _public_ int sd_bus_is_monitor(sd_bus *bus) {
3637         assert_return(bus, -EINVAL);
3638         assert_return(!bus_pid_changed(bus), -ECHILD);
3639
3640         return !!(bus->hello_flags & KDBUS_HELLO_MONITOR);
3641 }
3642
3643 static void flush_close(sd_bus *bus) {
3644         if (!bus)
3645                 return;
3646
3647         /* Flushes and closes the specified bus. We take a ref before,
3648          * to ensure the flushing does not cause the bus to be
3649          * unreferenced. */
3650
3651         sd_bus_flush_close_unref(sd_bus_ref(bus));
3652 }
3653
3654 _public_ void sd_bus_default_flush_close(void) {
3655         flush_close(default_starter_bus);
3656 #if 0 /// elogind does not support user buses
3657         flush_close(default_user_bus);
3658 #endif // 0
3659         flush_close(default_system_bus);
3660 }
3661
3662 _public_ int sd_bus_set_exit_on_disconnect(sd_bus *bus, int b) {
3663         assert_return(bus, -EINVAL);
3664
3665         /* Turns on exit-on-disconnect, and triggers it immediately if the bus connection was already
3666          * disconnected. Note that this is triggered exclusively on disconnections triggered by the server side, never
3667          * from the client side. */
3668         bus->exit_on_disconnect = b;
3669
3670         /* If the exit condition was triggered already, exit immediately. */
3671         return bus_exit_now(bus);
3672 }
3673
3674 _public_ int sd_bus_get_exit_on_disconnect(sd_bus *bus) {
3675         assert_return(bus, -EINVAL);
3676
3677         return bus->exit_on_disconnect;
3678 }