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