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