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