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