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