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