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