chiark / gitweb /
event: rework sd-event exit logic
[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         if (!filename_is_safe(machine))
768                 return -EINVAL;
769
770         free(b->machine);
771         b->machine = machine;
772         machine = NULL;
773
774         b->sockaddr.un.sun_family = AF_UNIX;
775         strncpy(b->sockaddr.un.sun_path, "/var/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
776         b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + sizeof("/var/run/dbus/system_bus_socket") - 1;
777
778         return 0;
779 }
780
781 static void bus_reset_parsed_address(sd_bus *b) {
782         assert(b);
783
784         zero(b->sockaddr);
785         b->sockaddr_size = 0;
786         strv_free(b->exec_argv);
787         free(b->exec_path);
788         b->exec_path = NULL;
789         b->exec_argv = NULL;
790         b->server_id = SD_ID128_NULL;
791         free(b->kernel);
792         b->kernel = NULL;
793         free(b->machine);
794         b->machine = NULL;
795 }
796
797 static int bus_parse_next_address(sd_bus *b) {
798         _cleanup_free_ char *guid = NULL;
799         const char *a;
800         int r;
801
802         assert(b);
803
804         if (!b->address)
805                 return 0;
806         if (b->address[b->address_index] == 0)
807                 return 0;
808
809         bus_reset_parsed_address(b);
810
811         a = b->address + b->address_index;
812
813         while (*a != 0) {
814
815                 if (*a == ';') {
816                         a++;
817                         continue;
818                 }
819
820                 if (startswith(a, "unix:")) {
821                         a += 5;
822
823                         r = parse_unix_address(b, &a, &guid);
824                         if (r < 0)
825                                 return r;
826                         break;
827
828                 } else if (startswith(a, "tcp:")) {
829
830                         a += 4;
831                         r = parse_tcp_address(b, &a, &guid);
832                         if (r < 0)
833                                 return r;
834
835                         break;
836
837                 } else if (startswith(a, "unixexec:")) {
838
839                         a += 9;
840                         r = parse_exec_address(b, &a, &guid);
841                         if (r < 0)
842                                 return r;
843
844                         break;
845
846                 } else if (startswith(a, "kernel:")) {
847
848                         a += 7;
849                         r = parse_kernel_address(b, &a, &guid);
850                         if (r < 0)
851                                 return r;
852
853                         break;
854                 } else if (startswith(a, "x-container:")) {
855
856                         a += 12;
857                         r = parse_container_address(b, &a, &guid);
858                         if (r < 0)
859                                 return r;
860
861                         break;
862                 }
863
864                 a = strchr(a, ';');
865                 if (!a)
866                         return 0;
867         }
868
869         if (guid) {
870                 r = sd_id128_from_string(guid, &b->server_id);
871                 if (r < 0)
872                         return r;
873         }
874
875         b->address_index = a - b->address;
876         return 1;
877 }
878
879 static int bus_start_address(sd_bus *b) {
880         int r;
881
882         assert(b);
883
884         for (;;) {
885                 sd_bus_close(b);
886
887                 if (b->exec_path) {
888
889                         r = bus_socket_exec(b);
890                         if (r >= 0)
891                                 return r;
892
893                         b->last_connect_error = -r;
894                 } else if (b->kernel) {
895
896                         r = bus_kernel_connect(b);
897                         if (r >= 0)
898                                 return r;
899
900                         b->last_connect_error = -r;
901
902                 } else if (b->machine) {
903
904                         r = bus_container_connect(b);
905                         if (r >= 0)
906                                 return r;
907
908                         b->last_connect_error = -r;
909
910                 } else if (b->sockaddr.sa.sa_family != AF_UNSPEC) {
911
912                         r = bus_socket_connect(b);
913                         if (r >= 0)
914                                 return r;
915
916                         b->last_connect_error = -r;
917                 }
918
919                 r = bus_parse_next_address(b);
920                 if (r < 0)
921                         return r;
922                 if (r == 0)
923                         return b->last_connect_error ? -b->last_connect_error : -ECONNREFUSED;
924         }
925 }
926
927 int bus_next_address(sd_bus *b) {
928         assert(b);
929
930         bus_reset_parsed_address(b);
931         return bus_start_address(b);
932 }
933
934 static int bus_start_fd(sd_bus *b) {
935         struct stat st;
936         int r;
937
938         assert(b);
939         assert(b->input_fd >= 0);
940         assert(b->output_fd >= 0);
941
942         r = fd_nonblock(b->input_fd, true);
943         if (r < 0)
944                 return r;
945
946         r = fd_cloexec(b->input_fd, true);
947         if (r < 0)
948                 return r;
949
950         if (b->input_fd != b->output_fd) {
951                 r = fd_nonblock(b->output_fd, true);
952                 if (r < 0)
953                         return r;
954
955                 r = fd_cloexec(b->output_fd, true);
956                 if (r < 0)
957                         return r;
958         }
959
960         if (fstat(b->input_fd, &st) < 0)
961                 return -errno;
962
963         if (S_ISCHR(b->input_fd))
964                 return bus_kernel_take_fd(b);
965         else
966                 return bus_socket_take_fd(b);
967 }
968
969 _public_ int sd_bus_start(sd_bus *bus) {
970         int r;
971
972         assert_return(bus, -EINVAL);
973         assert_return(bus->state == BUS_UNSET, -EPERM);
974         assert_return(!bus_pid_changed(bus), -ECHILD);
975
976         bus->state = BUS_OPENING;
977
978         if (bus->is_server && bus->bus_client)
979                 return -EINVAL;
980
981         if (bus->input_fd >= 0)
982                 r = bus_start_fd(bus);
983         else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->kernel || bus->machine)
984                 r = bus_start_address(bus);
985         else
986                 return -EINVAL;
987
988         if (r < 0)
989                 return r;
990
991         return bus_send_hello(bus);
992 }
993
994 _public_ int sd_bus_open_system(sd_bus **ret) {
995         const char *e;
996         sd_bus *b;
997         int r;
998
999         assert_return(ret, -EINVAL);
1000
1001         r = sd_bus_new(&b);
1002         if (r < 0)
1003                 return r;
1004
1005         e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1006         if (e)
1007                 r = sd_bus_set_address(b, e);
1008         else
1009 #ifdef ENABLE_KDBUS
1010                 r = sd_bus_set_address(b, "kernel:path=/dev/kdbus/0-system/bus;unix:path=/run/dbus/system_bus_socket");
1011 #else
1012                 r = sd_bus_set_address(b, "unix:path=/run/dbus/system_bus_socket");
1013 #endif
1014
1015         if (r < 0)
1016                 goto fail;
1017
1018         b->bus_client = true;
1019
1020         /* Let's do per-method access control on the system bus. We
1021          * need the caller's UID and capability set for that. */
1022         b->trusted = false;
1023         b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1024
1025         r = sd_bus_start(b);
1026         if (r < 0)
1027                 goto fail;
1028
1029         *ret = b;
1030         return 0;
1031
1032 fail:
1033         bus_free(b);
1034         return r;
1035 }
1036
1037 _public_ int sd_bus_open_user(sd_bus **ret) {
1038         const char *e;
1039         sd_bus *b;
1040         int r;
1041
1042         assert_return(ret, -EINVAL);
1043
1044         r = sd_bus_new(&b);
1045         if (r < 0)
1046                 return r;
1047
1048         e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
1049         if (e) {
1050                 r = sd_bus_set_address(b, e);
1051                 if (r < 0)
1052                         goto fail;
1053         } else {
1054                 e = secure_getenv("XDG_RUNTIME_DIR");
1055                 if (e) {
1056                         _cleanup_free_ char *ee = NULL;
1057
1058                         ee = bus_address_escape(e);
1059                         if (!ee) {
1060                                 r = -ENOMEM;
1061                                 goto fail;
1062                         }
1063
1064 #ifdef ENABLE_KDBUS
1065                         asprintf(&b->address, "kernel:path=/dev/kdbus/%lu-user/bus;unix:path=%s/bus", (unsigned long) getuid(), ee);
1066 #else
1067                         b->address = strjoin("unix:path=", ee, "/bus", NULL);
1068 #endif
1069                 } else {
1070 #ifdef ENABLE_KDBUS
1071                         asprintf(&b->address, "kernel:path=/dev/kdbus/%lu-user/bus", (unsigned long) getuid());
1072 #else
1073                         return -ECONNREFUSED;
1074 #endif
1075                 }
1076
1077                 if (!b->address) {
1078                         r = -ENOMEM;
1079                         goto fail;
1080                 }
1081         }
1082
1083         b->bus_client = true;
1084
1085         /* We don't do any per-method access control on the user
1086          * bus. */
1087         b->trusted = true;
1088
1089         r = sd_bus_start(b);
1090         if (r < 0)
1091                 goto fail;
1092
1093         *ret = b;
1094         return 0;
1095
1096 fail:
1097         bus_free(b);
1098         return r;
1099 }
1100
1101 _public_ int sd_bus_open_system_remote(const char *host, sd_bus **ret) {
1102         _cleanup_free_ char *e = NULL;
1103         char *p = NULL;
1104         sd_bus *bus;
1105         int r;
1106
1107         assert_return(host, -EINVAL);
1108         assert_return(ret, -EINVAL);
1109
1110         e = bus_address_escape(host);
1111         if (!e)
1112                 return -ENOMEM;
1113
1114         p = strjoin("unixexec:path=ssh,argv1=-xT,argv2=", e, ",argv3=systemd-stdio-bridge", NULL);
1115         if (!p)
1116                 return -ENOMEM;
1117
1118         r = sd_bus_new(&bus);
1119         if (r < 0) {
1120                 free(p);
1121                 return r;
1122         }
1123
1124         bus->address = p;
1125         bus->bus_client = true;
1126
1127         r = sd_bus_start(bus);
1128         if (r < 0) {
1129                 bus_free(bus);
1130                 return r;
1131         }
1132
1133         *ret = bus;
1134         return 0;
1135 }
1136
1137 _public_ int sd_bus_open_system_container(const char *machine, sd_bus **ret) {
1138         _cleanup_free_ char *e = NULL;
1139         sd_bus *bus;
1140         char *p;
1141         int r;
1142
1143         assert_return(machine, -EINVAL);
1144         assert_return(ret, -EINVAL);
1145         assert_return(filename_is_safe(machine), -EINVAL);
1146
1147         e = bus_address_escape(machine);
1148         if (!e)
1149                 return -ENOMEM;
1150
1151 #ifdef ENABLE_KDBUS
1152         p = strjoin("kernel:path=/dev/kdbus/ns/machine-", e, "/0-system/bus;x-container:machine=", e, NULL);
1153 #else
1154         p = strjoin("x-container:machine=", e, NULL);
1155 #endif
1156         if (!p)
1157                 return -ENOMEM;
1158
1159         r = sd_bus_new(&bus);
1160         if (r < 0) {
1161                 free(p);
1162                 return r;
1163         }
1164
1165         bus->address = p;
1166         bus->bus_client = true;
1167
1168         r = sd_bus_start(bus);
1169         if (r < 0) {
1170                 bus_free(bus);
1171                 return r;
1172         }
1173
1174         *ret = bus;
1175         return 0;
1176 }
1177
1178 _public_ void sd_bus_close(sd_bus *bus) {
1179
1180         if (!bus)
1181                 return;
1182         if (bus->state == BUS_CLOSED)
1183                 return;
1184         if (bus_pid_changed(bus))
1185                 return;
1186
1187         bus->state = BUS_CLOSED;
1188
1189         sd_bus_detach_event(bus);
1190
1191         /* Drop all queued messages so that they drop references to
1192          * the bus object and the bus may be freed */
1193         bus_reset_queues(bus);
1194
1195         if (!bus->is_kernel)
1196                 bus_close_fds(bus);
1197
1198         /* We'll leave the fd open in case this is a kernel bus, since
1199          * there might still be memblocks around that reference this
1200          * bus, and they might need to invoke the * KDBUS_CMD_FREE
1201          * ioctl on the fd when they are freed. */
1202 }
1203
1204 static void bus_enter_closing(sd_bus *bus) {
1205         assert(bus);
1206
1207         if (bus->state != BUS_OPENING &&
1208             bus->state != BUS_AUTHENTICATING &&
1209             bus->state != BUS_HELLO &&
1210             bus->state != BUS_RUNNING)
1211                 return;
1212
1213         bus->state = BUS_CLOSING;
1214 }
1215
1216 _public_ sd_bus *sd_bus_ref(sd_bus *bus) {
1217         assert_return(bus, NULL);
1218
1219         assert_se(REFCNT_INC(bus->n_ref) >= 2);
1220
1221         return bus;
1222 }
1223
1224 _public_ sd_bus *sd_bus_unref(sd_bus *bus) {
1225
1226         if (!bus)
1227                 return NULL;
1228
1229         if (REFCNT_DEC(bus->n_ref) <= 0)
1230                 bus_free(bus);
1231
1232         return NULL;
1233 }
1234
1235 _public_ int sd_bus_is_open(sd_bus *bus) {
1236
1237         assert_return(bus, -EINVAL);
1238         assert_return(!bus_pid_changed(bus), -ECHILD);
1239
1240         return BUS_IS_OPEN(bus->state);
1241 }
1242
1243 _public_ int sd_bus_can_send(sd_bus *bus, char type) {
1244         int r;
1245
1246         assert_return(bus, -EINVAL);
1247         assert_return(bus->state != BUS_UNSET, -ENOTCONN);
1248         assert_return(!bus_pid_changed(bus), -ECHILD);
1249
1250         if (type == SD_BUS_TYPE_UNIX_FD) {
1251                 if (!(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD))
1252                         return 0;
1253
1254                 r = bus_ensure_running(bus);
1255                 if (r < 0)
1256                         return r;
1257
1258                 return bus->can_fds;
1259         }
1260
1261         return bus_type_is_valid(type);
1262 }
1263
1264 _public_ int sd_bus_get_server_id(sd_bus *bus, sd_id128_t *server_id) {
1265         int r;
1266
1267         assert_return(bus, -EINVAL);
1268         assert_return(server_id, -EINVAL);
1269         assert_return(!bus_pid_changed(bus), -ECHILD);
1270
1271         r = bus_ensure_running(bus);
1272         if (r < 0)
1273                 return r;
1274
1275         *server_id = bus->server_id;
1276         return 0;
1277 }
1278
1279 static int bus_seal_message(sd_bus *b, sd_bus_message *m, usec_t timeout) {
1280         assert(b);
1281         assert(m);
1282
1283         if (b->message_version != 0 &&
1284             m->header->version != b->message_version)
1285                 return -EPERM;
1286
1287         if (b->message_endian != 0 &&
1288             m->header->endian != b->message_endian)
1289                 return -EPERM;
1290
1291         if (m->sealed) {
1292                 /* If we copy the same message to multiple
1293                  * destinations, avoid using the same serial
1294                  * numbers. */
1295                 b->serial = MAX(b->serial, BUS_MESSAGE_SERIAL(m));
1296                 return 0;
1297         }
1298
1299         if (timeout == 0)
1300                 timeout = BUS_DEFAULT_TIMEOUT;
1301
1302         return bus_message_seal(m, ++b->serial, timeout);
1303 }
1304
1305 int bus_seal_synthetic_message(sd_bus *b, sd_bus_message *m) {
1306         assert(b);
1307         assert(m);
1308
1309         /* The bus specification says the serial number cannot be 0,
1310          * hence let's fill something in for synthetic messages. Since
1311          * synthetic messages might have a fake sender and we don't
1312          * want to interfere with the real sender's serial numbers we
1313          * pick a fixed, artifical one. We use (uint32_t) -1 rather
1314          * than (uint64_t) -1 since dbus1 only had 32bit identifiers,
1315          * even though kdbus can do 64bit. */
1316
1317         return bus_message_seal(m, 0xFFFFFFFFULL, 0);
1318 }
1319
1320 static int bus_write_message(sd_bus *bus, sd_bus_message *message, size_t *idx) {
1321         assert(bus);
1322         assert(message);
1323
1324         if (bus->is_kernel)
1325                 return bus_kernel_write_message(bus, message);
1326         else
1327                 return bus_socket_write_message(bus, message, idx);
1328 }
1329
1330 static int dispatch_wqueue(sd_bus *bus) {
1331         int r, ret = 0;
1332
1333         assert(bus);
1334         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1335
1336         while (bus->wqueue_size > 0) {
1337
1338                 r = bus_write_message(bus, bus->wqueue[0], &bus->windex);
1339                 if (r < 0)
1340                         return r;
1341                 else if (r == 0)
1342                         /* Didn't do anything this time */
1343                         return ret;
1344                 else if (bus->is_kernel || bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
1345                         /* Fully written. Let's drop the entry from
1346                          * the queue.
1347                          *
1348                          * This isn't particularly optimized, but
1349                          * well, this is supposed to be our worst-case
1350                          * buffer only, and the socket buffer is
1351                          * supposed to be our primary buffer, and if
1352                          * it got full, then all bets are off
1353                          * anyway. */
1354
1355                         sd_bus_message_unref(bus->wqueue[0]);
1356                         bus->wqueue_size --;
1357                         memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
1358                         bus->windex = 0;
1359
1360                         ret = 1;
1361                 }
1362         }
1363
1364         return ret;
1365 }
1366
1367 static int bus_read_message(sd_bus *bus) {
1368         assert(bus);
1369
1370         if (bus->is_kernel)
1371                 return bus_kernel_read_message(bus);
1372         else
1373                 return bus_socket_read_message(bus);
1374 }
1375
1376 int bus_rqueue_make_room(sd_bus *bus) {
1377         sd_bus_message **q;
1378         unsigned x;
1379
1380         x = bus->rqueue_size + 1;
1381
1382         if (bus->rqueue_allocated >= x)
1383                 return 0;
1384
1385         if (x > BUS_RQUEUE_MAX)
1386                 return -ENOBUFS;
1387
1388         q = realloc(bus->rqueue, x * sizeof(sd_bus_message*));
1389         if (!q)
1390                 return -ENOMEM;
1391
1392         bus->rqueue = q;
1393         bus->rqueue_allocated = x;
1394
1395         return 0;
1396 }
1397
1398 static int dispatch_rqueue(sd_bus *bus, sd_bus_message **m) {
1399         int r, ret = 0;
1400
1401         assert(bus);
1402         assert(m);
1403         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1404
1405         for (;;) {
1406                 if (bus->rqueue_size > 0) {
1407                         /* Dispatch a queued message */
1408
1409                         *m = bus->rqueue[0];
1410                         bus->rqueue_size --;
1411                         memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
1412                         return 1;
1413                 }
1414
1415                 /* Try to read a new message */
1416                 r = bus_read_message(bus);
1417                 if (r < 0)
1418                         return r;
1419                 if (r == 0)
1420                         return ret;
1421
1422                 ret = 1;
1423         }
1424 }
1425
1426 _public_ int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *serial) {
1427         int r;
1428
1429         assert_return(bus, -EINVAL);
1430         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1431         assert_return(m, -EINVAL);
1432         assert_return(!bus_pid_changed(bus), -ECHILD);
1433
1434         if (m->n_fds > 0) {
1435                 r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
1436                 if (r < 0)
1437                         return r;
1438                 if (r == 0)
1439                         return -ENOTSUP;
1440         }
1441
1442         /* If the serial number isn't kept, then we know that no reply
1443          * is expected */
1444         if (!serial && !m->sealed)
1445                 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1446
1447         r = bus_seal_message(bus, m, 0);
1448         if (r < 0)
1449                 return r;
1450
1451         /* If this is a reply and no reply was requested, then let's
1452          * suppress this, if we can */
1453         if (m->dont_send && !serial)
1454                 return 1;
1455
1456         if ((bus->state == BUS_RUNNING || bus->state == BUS_HELLO) && bus->wqueue_size <= 0) {
1457                 size_t idx = 0;
1458
1459                 r = bus_write_message(bus, m, &idx);
1460                 if (r < 0) {
1461                         if (r == -EPIPE || r == -ENOTCONN || r == -ESHUTDOWN)
1462                                 bus_enter_closing(bus);
1463
1464                         return r;
1465                 } else if (!bus->is_kernel && idx < BUS_MESSAGE_SIZE(m))  {
1466                         /* Wasn't fully written. So let's remember how
1467                          * much was written. Note that the first entry
1468                          * of the wqueue array is always allocated so
1469                          * that we always can remember how much was
1470                          * written. */
1471                         bus->wqueue[0] = sd_bus_message_ref(m);
1472                         bus->wqueue_size = 1;
1473                         bus->windex = idx;
1474                 }
1475         } else {
1476                 sd_bus_message **q;
1477
1478                 /* Just append it to the queue. */
1479
1480                 if (bus->wqueue_size >= BUS_WQUEUE_MAX)
1481                         return -ENOBUFS;
1482
1483                 q = realloc(bus->wqueue, sizeof(sd_bus_message*) * (bus->wqueue_size + 1));
1484                 if (!q)
1485                         return -ENOMEM;
1486
1487                 bus->wqueue = q;
1488                 q[bus->wqueue_size ++] = sd_bus_message_ref(m);
1489         }
1490
1491         if (serial)
1492                 *serial = BUS_MESSAGE_SERIAL(m);
1493
1494         return 1;
1495 }
1496
1497 _public_ int sd_bus_send_to(sd_bus *bus, sd_bus_message *m, const char *destination, uint64_t *serial) {
1498         int r;
1499
1500         assert_return(bus, -EINVAL);
1501         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1502         assert_return(m, -EINVAL);
1503         assert_return(!bus_pid_changed(bus), -ECHILD);
1504
1505         if (!streq_ptr(m->destination, destination)) {
1506
1507                 if (!destination)
1508                         return -EEXIST;
1509
1510                 r = sd_bus_message_set_destination(m, destination);
1511                 if (r < 0)
1512                         return r;
1513         }
1514
1515         return sd_bus_send(bus, m, serial);
1516 }
1517
1518 static usec_t calc_elapse(uint64_t usec) {
1519         if (usec == (uint64_t) -1)
1520                 return 0;
1521
1522         return now(CLOCK_MONOTONIC) + usec;
1523 }
1524
1525 static int timeout_compare(const void *a, const void *b) {
1526         const struct reply_callback *x = a, *y = b;
1527
1528         if (x->timeout != 0 && y->timeout == 0)
1529                 return -1;
1530
1531         if (x->timeout == 0 && y->timeout != 0)
1532                 return 1;
1533
1534         if (x->timeout < y->timeout)
1535                 return -1;
1536
1537         if (x->timeout > y->timeout)
1538                 return 1;
1539
1540         return 0;
1541 }
1542
1543 _public_ int sd_bus_call_async(
1544                 sd_bus *bus,
1545                 sd_bus_message *m,
1546                 sd_bus_message_handler_t callback,
1547                 void *userdata,
1548                 uint64_t usec,
1549                 uint64_t *serial) {
1550
1551         struct reply_callback *c;
1552         int r;
1553
1554         assert_return(bus, -EINVAL);
1555         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1556         assert_return(m, -EINVAL);
1557         assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1558         assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1559         assert_return(callback, -EINVAL);
1560         assert_return(!bus_pid_changed(bus), -ECHILD);
1561
1562         r = hashmap_ensure_allocated(&bus->reply_callbacks, uint64_hash_func, uint64_compare_func);
1563         if (r < 0)
1564                 return r;
1565
1566         r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
1567         if (r < 0)
1568                 return r;
1569
1570         r = bus_seal_message(bus, m, usec);
1571         if (r < 0)
1572                 return r;
1573
1574         c = new0(struct reply_callback, 1);
1575         if (!c)
1576                 return -ENOMEM;
1577
1578         c->callback = callback;
1579         c->userdata = userdata;
1580         c->serial = BUS_MESSAGE_SERIAL(m);
1581         c->timeout = calc_elapse(m->timeout);
1582
1583         r = hashmap_put(bus->reply_callbacks, &c->serial, c);
1584         if (r < 0) {
1585                 free(c);
1586                 return r;
1587         }
1588
1589         if (c->timeout != 0) {
1590                 r = prioq_put(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1591                 if (r < 0) {
1592                         c->timeout = 0;
1593                         sd_bus_call_async_cancel(bus, c->serial);
1594                         return r;
1595                 }
1596         }
1597
1598         r = sd_bus_send(bus, m, serial);
1599         if (r < 0) {
1600                 sd_bus_call_async_cancel(bus, c->serial);
1601                 return r;
1602         }
1603
1604         return r;
1605 }
1606
1607 _public_ int sd_bus_call_async_cancel(sd_bus *bus, uint64_t serial) {
1608         struct reply_callback *c;
1609
1610         assert_return(bus, -EINVAL);
1611         assert_return(serial != 0, -EINVAL);
1612         assert_return(!bus_pid_changed(bus), -ECHILD);
1613
1614         c = hashmap_remove(bus->reply_callbacks, &serial);
1615         if (!c)
1616                 return 0;
1617
1618         if (c->timeout != 0)
1619                 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1620
1621         free(c);
1622         return 1;
1623 }
1624
1625 int bus_ensure_running(sd_bus *bus) {
1626         int r;
1627
1628         assert(bus);
1629
1630         if (bus->state == BUS_UNSET || bus->state == BUS_CLOSED || bus->state == BUS_CLOSING)
1631                 return -ENOTCONN;
1632         if (bus->state == BUS_RUNNING)
1633                 return 1;
1634
1635         for (;;) {
1636                 r = sd_bus_process(bus, NULL);
1637                 if (r < 0)
1638                         return r;
1639                 if (bus->state == BUS_RUNNING)
1640                         return 1;
1641                 if (r > 0)
1642                         continue;
1643
1644                 r = sd_bus_wait(bus, (uint64_t) -1);
1645                 if (r < 0)
1646                         return r;
1647         }
1648 }
1649
1650 _public_ int sd_bus_call(
1651                 sd_bus *bus,
1652                 sd_bus_message *m,
1653                 uint64_t usec,
1654                 sd_bus_error *error,
1655                 sd_bus_message **reply) {
1656
1657         usec_t timeout;
1658         uint64_t serial;
1659         unsigned i;
1660         int r;
1661
1662         assert_return(bus, -EINVAL);
1663         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1664         assert_return(m, -EINVAL);
1665         assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1666         assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1667         assert_return(!bus_error_is_dirty(error), -EINVAL);
1668         assert_return(!bus_pid_changed(bus), -ECHILD);
1669
1670         r = bus_ensure_running(bus);
1671         if (r < 0)
1672                 return r;
1673
1674         i = bus->rqueue_size;
1675
1676         r = bus_seal_message(bus, m, usec);
1677         if (r < 0)
1678                 return r;
1679
1680         r = sd_bus_send(bus, m, &serial);
1681         if (r < 0)
1682                 return r;
1683
1684         timeout = calc_elapse(m->timeout);
1685
1686         for (;;) {
1687                 usec_t left;
1688
1689                 while (i < bus->rqueue_size) {
1690                         sd_bus_message *incoming = NULL;
1691
1692                         incoming = bus->rqueue[i];
1693
1694                         if (incoming->reply_serial == serial) {
1695                                 /* Found a match! */
1696
1697                                 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1698                                 bus->rqueue_size--;
1699
1700                                 if (incoming->header->type == SD_BUS_MESSAGE_METHOD_RETURN) {
1701
1702                                         if (reply)
1703                                                 *reply = incoming;
1704                                         else
1705                                                 sd_bus_message_unref(incoming);
1706
1707                                         return 1;
1708                                 } else if (incoming->header->type == SD_BUS_MESSAGE_METHOD_ERROR)
1709                                         r = sd_bus_error_copy(error, &incoming->error);
1710                                 else
1711                                         r = -EIO;
1712
1713                                 sd_bus_message_unref(incoming);
1714                                 return r;
1715
1716                         } else if (incoming->header->serial == serial &&
1717                                    bus->unique_name &&
1718                                    incoming->sender &&
1719                                    streq(bus->unique_name, incoming->sender)) {
1720
1721                                 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1722                                 bus->rqueue_size--;
1723
1724                                 /* Our own message? Somebody is trying
1725                                  * to send its own client a message,
1726                                  * let's not dead-lock, let's fail
1727                                  * immediately. */
1728
1729                                 sd_bus_message_unref(incoming);
1730                                 return -ELOOP;
1731                         }
1732
1733                         /* Try to read more, right-away */
1734                         i++;
1735                 }
1736
1737                 r = bus_read_message(bus);
1738                 if (r < 0) {
1739                         if (r == -EPIPE || r == -ENOTCONN || r == -ESHUTDOWN)
1740                                 bus_enter_closing(bus);
1741
1742                         return r;
1743                 }
1744                 if (r > 0)
1745                         continue;
1746
1747                 if (timeout > 0) {
1748                         usec_t n;
1749
1750                         n = now(CLOCK_MONOTONIC);
1751                         if (n >= timeout)
1752                                 return -ETIMEDOUT;
1753
1754                         left = timeout - n;
1755                 } else
1756                         left = (uint64_t) -1;
1757
1758                 r = bus_poll(bus, true, left);
1759                 if (r < 0)
1760                         return r;
1761                 if (r == 0)
1762                         return -ETIMEDOUT;
1763
1764                 r = dispatch_wqueue(bus);
1765                 if (r < 0) {
1766                         if (r == -EPIPE || r == -ENOTCONN || r == -ESHUTDOWN)
1767                                 bus_enter_closing(bus);
1768
1769                         return r;
1770                 }
1771         }
1772 }
1773
1774 _public_ int sd_bus_get_fd(sd_bus *bus) {
1775
1776         assert_return(bus, -EINVAL);
1777         assert_return(bus->input_fd == bus->output_fd, -EPERM);
1778         assert_return(!bus_pid_changed(bus), -ECHILD);
1779
1780         return bus->input_fd;
1781 }
1782
1783 _public_ int sd_bus_get_events(sd_bus *bus) {
1784         int flags = 0;
1785
1786         assert_return(bus, -EINVAL);
1787         assert_return(BUS_IS_OPEN(bus->state) || bus->state == BUS_CLOSING, -ENOTCONN);
1788         assert_return(!bus_pid_changed(bus), -ECHILD);
1789
1790         if (bus->state == BUS_OPENING)
1791                 flags |= POLLOUT;
1792         else if (bus->state == BUS_AUTHENTICATING) {
1793
1794                 if (bus_socket_auth_needs_write(bus))
1795                         flags |= POLLOUT;
1796
1797                 flags |= POLLIN;
1798
1799         } else if (bus->state == BUS_RUNNING || bus->state == BUS_HELLO) {
1800                 if (bus->rqueue_size <= 0)
1801                         flags |= POLLIN;
1802                 if (bus->wqueue_size > 0)
1803                         flags |= POLLOUT;
1804         }
1805
1806         return flags;
1807 }
1808
1809 _public_ int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
1810         struct reply_callback *c;
1811
1812         assert_return(bus, -EINVAL);
1813         assert_return(timeout_usec, -EINVAL);
1814         assert_return(BUS_IS_OPEN(bus->state) || bus->state == BUS_CLOSING, -ENOTCONN);
1815         assert_return(!bus_pid_changed(bus), -ECHILD);
1816
1817         if (bus->state == BUS_CLOSING) {
1818                 *timeout_usec = 0;
1819                 return 1;
1820         }
1821
1822         if (bus->state == BUS_AUTHENTICATING) {
1823                 *timeout_usec = bus->auth_timeout;
1824                 return 1;
1825         }
1826
1827         if (bus->state != BUS_RUNNING && bus->state != BUS_HELLO) {
1828                 *timeout_usec = (uint64_t) -1;
1829                 return 0;
1830         }
1831
1832         if (bus->rqueue_size > 0) {
1833                 *timeout_usec = 0;
1834                 return 1;
1835         }
1836
1837         c = prioq_peek(bus->reply_callbacks_prioq);
1838         if (!c) {
1839                 *timeout_usec = (uint64_t) -1;
1840                 return 0;
1841         }
1842
1843         *timeout_usec = c->timeout;
1844         return 1;
1845 }
1846
1847 static int process_timeout(sd_bus *bus) {
1848         _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
1849         _cleanup_bus_message_unref_ sd_bus_message* m = NULL;
1850         struct reply_callback *c;
1851         usec_t n;
1852         int r;
1853
1854         assert(bus);
1855
1856         c = prioq_peek(bus->reply_callbacks_prioq);
1857         if (!c)
1858                 return 0;
1859
1860         n = now(CLOCK_MONOTONIC);
1861         if (c->timeout > n)
1862                 return 0;
1863
1864         r = bus_message_new_synthetic_error(
1865                         bus,
1866                         c->serial,
1867                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
1868                         &m);
1869         if (r < 0)
1870                 return r;
1871
1872         m->sender = "org.freedesktop.DBus";
1873
1874         r = bus_seal_synthetic_message(bus, m);
1875         if (r < 0)
1876                 return r;
1877
1878         assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
1879         hashmap_remove(bus->reply_callbacks, &c->serial);
1880
1881         bus->current = m;
1882         bus->iteration_counter ++;
1883
1884         r = c->callback(bus, m, c->userdata, &error_buffer);
1885         r = bus_maybe_reply_error(m, r, &error_buffer);
1886         free(c);
1887
1888         bus->current = NULL;
1889
1890         return r;
1891 }
1892
1893 static int process_hello(sd_bus *bus, sd_bus_message *m) {
1894         assert(bus);
1895         assert(m);
1896
1897         if (bus->state != BUS_HELLO)
1898                 return 0;
1899
1900         /* Let's make sure the first message on the bus is the HELLO
1901          * reply. But note that we don't actually parse the message
1902          * here (we leave that to the usual handling), we just verify
1903          * we don't let any earlier msg through. */
1904
1905         if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
1906             m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
1907                 return -EIO;
1908
1909         if (m->reply_serial != bus->hello_serial)
1910                 return -EIO;
1911
1912         return 0;
1913 }
1914
1915 static int process_reply(sd_bus *bus, sd_bus_message *m) {
1916         _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
1917         struct reply_callback *c;
1918         int r;
1919
1920         assert(bus);
1921         assert(m);
1922
1923         if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
1924             m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
1925                 return 0;
1926
1927         c = hashmap_remove(bus->reply_callbacks, &m->reply_serial);
1928         if (!c)
1929                 return 0;
1930
1931         if (c->timeout != 0)
1932                 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1933
1934         r = sd_bus_message_rewind(m, true);
1935         if (r < 0)
1936                 return r;
1937
1938         r = c->callback(bus, m, c->userdata, &error_buffer);
1939         r = bus_maybe_reply_error(m, r, &error_buffer);
1940         free(c);
1941
1942         return r;
1943 }
1944
1945 static int process_filter(sd_bus *bus, sd_bus_message *m) {
1946         _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
1947         struct filter_callback *l;
1948         int r;
1949
1950         assert(bus);
1951         assert(m);
1952
1953         do {
1954                 bus->filter_callbacks_modified = false;
1955
1956                 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
1957
1958                         if (bus->filter_callbacks_modified)
1959                                 break;
1960
1961                         /* Don't run this more than once per iteration */
1962                         if (l->last_iteration == bus->iteration_counter)
1963                                 continue;
1964
1965                         l->last_iteration = bus->iteration_counter;
1966
1967                         r = sd_bus_message_rewind(m, true);
1968                         if (r < 0)
1969                                 return r;
1970
1971                         r = l->callback(bus, m, l->userdata, &error_buffer);
1972                         r = bus_maybe_reply_error(m, r, &error_buffer);
1973                         if (r != 0)
1974                                 return r;
1975
1976                 }
1977
1978         } while (bus->filter_callbacks_modified);
1979
1980         return 0;
1981 }
1982
1983 static int process_match(sd_bus *bus, sd_bus_message *m) {
1984         int r;
1985
1986         assert(bus);
1987         assert(m);
1988
1989         do {
1990                 bus->match_callbacks_modified = false;
1991
1992                 r = bus_match_run(bus, &bus->match_callbacks, m);
1993                 if (r != 0)
1994                         return r;
1995
1996         } while (bus->match_callbacks_modified);
1997
1998         return 0;
1999 }
2000
2001 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
2002         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
2003         int r;
2004
2005         assert(bus);
2006         assert(m);
2007
2008         if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2009                 return 0;
2010
2011         if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2012                 return 0;
2013
2014         if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2015                 return 1;
2016
2017         if (streq_ptr(m->member, "Ping"))
2018                 r = sd_bus_message_new_method_return(m, &reply);
2019         else if (streq_ptr(m->member, "GetMachineId")) {
2020                 sd_id128_t id;
2021                 char sid[33];
2022
2023                 r = sd_id128_get_machine(&id);
2024                 if (r < 0)
2025                         return r;
2026
2027                 r = sd_bus_message_new_method_return(m, &reply);
2028                 if (r < 0)
2029                         return r;
2030
2031                 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2032         } else {
2033                 r = sd_bus_message_new_method_errorf(
2034                                 m, &reply,
2035                                 SD_BUS_ERROR_UNKNOWN_METHOD,
2036                                  "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2037         }
2038
2039         if (r < 0)
2040                 return r;
2041
2042         r = sd_bus_send(bus, reply, NULL);
2043         if (r < 0)
2044                 return r;
2045
2046         return 1;
2047 }
2048
2049 static int process_message(sd_bus *bus, sd_bus_message *m) {
2050         int r;
2051
2052         assert(bus);
2053         assert(m);
2054
2055         bus->current = m;
2056         bus->iteration_counter++;
2057
2058         log_debug("Got message sender=%s object=%s interface=%s member=%s",
2059                   strna(sd_bus_message_get_sender(m)),
2060                   strna(sd_bus_message_get_path(m)),
2061                   strna(sd_bus_message_get_interface(m)),
2062                   strna(sd_bus_message_get_member(m)));
2063
2064         r = process_hello(bus, m);
2065         if (r != 0)
2066                 goto finish;
2067
2068         r = process_reply(bus, m);
2069         if (r != 0)
2070                 goto finish;
2071
2072         r = process_filter(bus, m);
2073         if (r != 0)
2074                 goto finish;
2075
2076         r = process_match(bus, m);
2077         if (r != 0)
2078                 goto finish;
2079
2080         r = process_builtin(bus, m);
2081         if (r != 0)
2082                 goto finish;
2083
2084         r = bus_process_object(bus, m);
2085
2086 finish:
2087         bus->current = NULL;
2088         return r;
2089 }
2090
2091 static int process_running(sd_bus *bus, sd_bus_message **ret) {
2092         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2093         int r;
2094
2095         assert(bus);
2096         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
2097
2098         r = process_timeout(bus);
2099         if (r != 0)
2100                 goto null_message;
2101
2102         r = dispatch_wqueue(bus);
2103         if (r != 0)
2104                 goto null_message;
2105
2106         r = dispatch_rqueue(bus, &m);
2107         if (r < 0)
2108                 return r;
2109         if (!m)
2110                 goto null_message;
2111
2112         r = process_message(bus, m);
2113         if (r != 0)
2114                 goto null_message;
2115
2116         if (ret) {
2117                 r = sd_bus_message_rewind(m, true);
2118                 if (r < 0)
2119                         return r;
2120
2121                 *ret = m;
2122                 m = NULL;
2123                 return 1;
2124         }
2125
2126         if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2127
2128                 r = sd_bus_reply_method_errorf(
2129                                 m,
2130                                 SD_BUS_ERROR_UNKNOWN_OBJECT,
2131                                 "Unknown object '%s'.", m->path);
2132                 if (r < 0)
2133                         return r;
2134         }
2135
2136         return 1;
2137
2138 null_message:
2139         if (r >= 0 && ret)
2140                 *ret = NULL;
2141
2142         return r;
2143 }
2144
2145 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2146         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2147         struct reply_callback *c;
2148         int r;
2149
2150         assert(bus);
2151         assert(bus->state == BUS_CLOSING);
2152
2153         c = hashmap_first(bus->reply_callbacks);
2154         if (c) {
2155                 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2156
2157                 /* First, fail all outstanding method calls */
2158                 r = bus_message_new_synthetic_error(
2159                                 bus,
2160                                 c->serial,
2161                                 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2162                                 &m);
2163                 if (r < 0)
2164                         return r;
2165
2166                 r = bus_seal_synthetic_message(bus, m);
2167                 if (r < 0)
2168                         return r;
2169
2170                 if (c->timeout != 0)
2171                         prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2172
2173                 hashmap_remove(bus->reply_callbacks, &c->serial);
2174
2175                 bus->current = m;
2176                 bus->iteration_counter++;
2177
2178                 r = c->callback(bus, m, c->userdata, &error_buffer);
2179                 r = bus_maybe_reply_error(m, r, &error_buffer);
2180                 free(c);
2181
2182                 goto finish;
2183         }
2184
2185         /* Then, synthesize a Disconnected message */
2186         r = sd_bus_message_new_signal(
2187                         bus,
2188                         "/org/freedesktop/DBus/Local",
2189                         "org.freedesktop.DBus.Local",
2190                         "Disconnected",
2191                         &m);
2192         if (r < 0)
2193                 return r;
2194
2195         m->sender = "org.freedesktop.DBus.Local";
2196
2197         r = bus_seal_synthetic_message(bus, m);
2198         if (r < 0)
2199                 return r;
2200
2201         sd_bus_close(bus);
2202
2203         bus->current = m;
2204         bus->iteration_counter++;
2205
2206         r = process_filter(bus, m);
2207         if (r != 0)
2208                 goto finish;
2209
2210         r = process_match(bus, m);
2211         if (r != 0)
2212                 goto finish;
2213
2214         if (ret) {
2215                 *ret = m;
2216                 m = NULL;
2217         }
2218
2219         r = 1;
2220
2221 finish:
2222         bus->current = NULL;
2223         return r;
2224 }
2225
2226 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2227         BUS_DONT_DESTROY(bus);
2228         int r;
2229
2230         /* Returns 0 when we didn't do anything. This should cause the
2231          * caller to invoke sd_bus_wait() before returning the next
2232          * time. Returns > 0 when we did something, which possibly
2233          * means *ret is filled in with an unprocessed message. */
2234
2235         assert_return(bus, -EINVAL);
2236         assert_return(!bus_pid_changed(bus), -ECHILD);
2237
2238         /* We don't allow recursively invoking sd_bus_process(). */
2239         assert_return(!bus->current, -EBUSY);
2240
2241         switch (bus->state) {
2242
2243         case BUS_UNSET:
2244         case BUS_CLOSED:
2245                 return -ENOTCONN;
2246
2247         case BUS_OPENING:
2248                 r = bus_socket_process_opening(bus);
2249                 if (r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2250                         bus_enter_closing(bus);
2251                         r = 1;
2252                 } else if (r < 0)
2253                         return r;
2254                 if (ret)
2255                         *ret = NULL;
2256                 return r;
2257
2258         case BUS_AUTHENTICATING:
2259                 r = bus_socket_process_authenticating(bus);
2260                 if (r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2261                         bus_enter_closing(bus);
2262                         r = 1;
2263                 } else if (r < 0)
2264                         return r;
2265
2266                 if (ret)
2267                         *ret = NULL;
2268
2269                 return r;
2270
2271         case BUS_RUNNING:
2272         case BUS_HELLO:
2273                 r = process_running(bus, ret);
2274                 if (r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2275                         bus_enter_closing(bus);
2276                         r = 1;
2277
2278                         if (ret)
2279                                 *ret = NULL;
2280                 }
2281
2282                 return r;
2283
2284         case BUS_CLOSING:
2285                 return process_closing(bus, ret);
2286         }
2287
2288         assert_not_reached("Unknown state");
2289 }
2290
2291 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2292         struct pollfd p[2] = {};
2293         int r, e, n;
2294         struct timespec ts;
2295         usec_t m = (usec_t) -1;
2296
2297         assert(bus);
2298
2299         if (bus->state == BUS_CLOSING)
2300                 return 1;
2301
2302         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2303
2304         e = sd_bus_get_events(bus);
2305         if (e < 0)
2306                 return e;
2307
2308         if (need_more)
2309                 /* The caller really needs some more data, he doesn't
2310                  * care about what's already read, or any timeouts
2311                  * except its own.*/
2312                 e |= POLLIN;
2313         else {
2314                 usec_t until;
2315                 /* The caller wants to process if there's something to
2316                  * process, but doesn't care otherwise */
2317
2318                 r = sd_bus_get_timeout(bus, &until);
2319                 if (r < 0)
2320                         return r;
2321                 if (r > 0) {
2322                         usec_t nw;
2323                         nw = now(CLOCK_MONOTONIC);
2324                         m = until > nw ? until - nw : 0;
2325                 }
2326         }
2327
2328         if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
2329                 m = timeout_usec;
2330
2331         p[0].fd = bus->input_fd;
2332         if (bus->output_fd == bus->input_fd) {
2333                 p[0].events = e;
2334                 n = 1;
2335         } else {
2336                 p[0].events = e & POLLIN;
2337                 p[1].fd = bus->output_fd;
2338                 p[1].events = e & POLLOUT;
2339                 n = 2;
2340         }
2341
2342         r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
2343         if (r < 0)
2344                 return -errno;
2345
2346         return r > 0 ? 1 : 0;
2347 }
2348
2349 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
2350
2351         assert_return(bus, -EINVAL);
2352         assert_return(!bus_pid_changed(bus), -ECHILD);
2353
2354         if (bus->state == BUS_CLOSING)
2355                 return 0;
2356
2357         assert_return(BUS_IS_OPEN(bus->state) , -ENOTCONN);
2358
2359         if (bus->rqueue_size > 0)
2360                 return 0;
2361
2362         return bus_poll(bus, false, timeout_usec);
2363 }
2364
2365 _public_ int sd_bus_flush(sd_bus *bus) {
2366         int r;
2367
2368         assert_return(bus, -EINVAL);
2369         assert_return(!bus_pid_changed(bus), -ECHILD);
2370
2371         if (bus->state == BUS_CLOSING)
2372                 return 0;
2373
2374         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2375
2376         r = bus_ensure_running(bus);
2377         if (r < 0)
2378                 return r;
2379
2380         if (bus->wqueue_size <= 0)
2381                 return 0;
2382
2383         for (;;) {
2384                 r = dispatch_wqueue(bus);
2385                 if (r < 0) {
2386                         if (r == -EPIPE || r == -ENOTCONN || r == -ESHUTDOWN)
2387                                 bus_enter_closing(bus);
2388
2389                         return r;
2390                 }
2391
2392                 if (bus->wqueue_size <= 0)
2393                         return 0;
2394
2395                 r = bus_poll(bus, false, (uint64_t) -1);
2396                 if (r < 0)
2397                         return r;
2398         }
2399 }
2400
2401 _public_ int sd_bus_add_filter(sd_bus *bus,
2402                                sd_bus_message_handler_t callback,
2403                                void *userdata) {
2404
2405         struct filter_callback *f;
2406
2407         assert_return(bus, -EINVAL);
2408         assert_return(callback, -EINVAL);
2409         assert_return(!bus_pid_changed(bus), -ECHILD);
2410
2411         f = new0(struct filter_callback, 1);
2412         if (!f)
2413                 return -ENOMEM;
2414         f->callback = callback;
2415         f->userdata = userdata;
2416
2417         bus->filter_callbacks_modified = true;
2418         LIST_PREPEND(callbacks, bus->filter_callbacks, f);
2419         return 0;
2420 }
2421
2422 _public_ int sd_bus_remove_filter(sd_bus *bus,
2423                                   sd_bus_message_handler_t callback,
2424                                   void *userdata) {
2425
2426         struct filter_callback *f;
2427
2428         assert_return(bus, -EINVAL);
2429         assert_return(callback, -EINVAL);
2430         assert_return(!bus_pid_changed(bus), -ECHILD);
2431
2432         LIST_FOREACH(callbacks, f, bus->filter_callbacks) {
2433                 if (f->callback == callback && f->userdata == userdata) {
2434                         bus->filter_callbacks_modified = true;
2435                         LIST_REMOVE(callbacks, bus->filter_callbacks, f);
2436                         free(f);
2437                         return 1;
2438                 }
2439         }
2440
2441         return 0;
2442 }
2443
2444 _public_ int sd_bus_add_match(sd_bus *bus,
2445                               const char *match,
2446                               sd_bus_message_handler_t callback,
2447                               void *userdata) {
2448
2449         struct bus_match_component *components = NULL;
2450         unsigned n_components = 0;
2451         uint64_t cookie = 0;
2452         int r = 0;
2453
2454         assert_return(bus, -EINVAL);
2455         assert_return(match, -EINVAL);
2456         assert_return(!bus_pid_changed(bus), -ECHILD);
2457
2458         r = bus_match_parse(match, &components, &n_components);
2459         if (r < 0)
2460                 goto finish;
2461
2462         if (bus->bus_client) {
2463                 cookie = ++bus->match_cookie;
2464
2465                 r = bus_add_match_internal(bus, match, components, n_components, cookie);
2466                 if (r < 0)
2467                         goto finish;
2468         }
2469
2470         bus->match_callbacks_modified = true;
2471         r = bus_match_add(&bus->match_callbacks, components, n_components, callback, userdata, cookie, NULL);
2472         if (r < 0) {
2473                 if (bus->bus_client)
2474                         bus_remove_match_internal(bus, match, cookie);
2475         }
2476
2477 finish:
2478         bus_match_parse_free(components, n_components);
2479         return r;
2480 }
2481
2482 _public_ int sd_bus_remove_match(sd_bus *bus,
2483                                  const char *match,
2484                                  sd_bus_message_handler_t callback,
2485                                  void *userdata) {
2486
2487         struct bus_match_component *components = NULL;
2488         unsigned n_components = 0;
2489         int r = 0, q = 0;
2490         uint64_t cookie = 0;
2491
2492         assert_return(bus, -EINVAL);
2493         assert_return(match, -EINVAL);
2494         assert_return(!bus_pid_changed(bus), -ECHILD);
2495
2496         r = bus_match_parse(match, &components, &n_components);
2497         if (r < 0)
2498                 return r;
2499
2500         bus->match_callbacks_modified = true;
2501         r = bus_match_remove(&bus->match_callbacks, components, n_components, callback, userdata, &cookie);
2502
2503         if (bus->bus_client)
2504                 q = bus_remove_match_internal(bus, match, cookie);
2505
2506         bus_match_parse_free(components, n_components);
2507
2508         return r < 0 ? r : q;
2509 }
2510
2511 bool bus_pid_changed(sd_bus *bus) {
2512         assert(bus);
2513
2514         /* We don't support people creating a bus connection and
2515          * keeping it around over a fork(). Let's complain. */
2516
2517         return bus->original_pid != getpid();
2518 }
2519
2520 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2521         sd_bus *bus = userdata;
2522         int r;
2523
2524         assert(bus);
2525
2526         r = sd_bus_process(bus, NULL);
2527         if (r < 0)
2528                 return r;
2529
2530         return 1;
2531 }
2532
2533 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
2534         sd_bus *bus = userdata;
2535         int r;
2536
2537         assert(bus);
2538
2539         r = sd_bus_process(bus, NULL);
2540         if (r < 0)
2541                 return r;
2542
2543         return 1;
2544 }
2545
2546 static int prepare_callback(sd_event_source *s, void *userdata) {
2547         sd_bus *bus = userdata;
2548         int r, e;
2549         usec_t until;
2550
2551         assert(s);
2552         assert(bus);
2553
2554         e = sd_bus_get_events(bus);
2555         if (e < 0)
2556                 return e;
2557
2558         if (bus->output_fd != bus->input_fd) {
2559
2560                 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
2561                 if (r < 0)
2562                         return r;
2563
2564                 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
2565                 if (r < 0)
2566                         return r;
2567         } else {
2568                 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
2569                 if (r < 0)
2570                         return r;
2571         }
2572
2573         r = sd_bus_get_timeout(bus, &until);
2574         if (r < 0)
2575                 return r;
2576         if (r > 0) {
2577                 int j;
2578
2579                 j = sd_event_source_set_time(bus->time_event_source, until);
2580                 if (j < 0)
2581                         return j;
2582         }
2583
2584         r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
2585         if (r < 0)
2586                 return r;
2587
2588         return 1;
2589 }
2590
2591 static int quit_callback(sd_event_source *event, void *userdata) {
2592         sd_bus *bus = userdata;
2593
2594         assert(event);
2595
2596         sd_bus_flush(bus);
2597
2598         return 1;
2599 }
2600
2601 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
2602         int r;
2603
2604         assert_return(bus, -EINVAL);
2605         assert_return(!bus->event, -EBUSY);
2606
2607         assert(!bus->input_io_event_source);
2608         assert(!bus->output_io_event_source);
2609         assert(!bus->time_event_source);
2610
2611         if (event)
2612                 bus->event = sd_event_ref(event);
2613         else  {
2614                 r = sd_event_default(&bus->event);
2615                 if (r < 0)
2616                         return r;
2617         }
2618
2619         r = sd_event_add_io(bus->event, bus->input_fd, 0, io_callback, bus, &bus->input_io_event_source);
2620         if (r < 0)
2621                 goto fail;
2622
2623         r = sd_event_source_set_priority(bus->input_io_event_source, priority);
2624         if (r < 0)
2625                 goto fail;
2626
2627         if (bus->output_fd != bus->input_fd) {
2628                 r = sd_event_add_io(bus->event, bus->output_fd, 0, io_callback, bus, &bus->output_io_event_source);
2629                 if (r < 0)
2630                         goto fail;
2631
2632                 r = sd_event_source_set_priority(bus->output_io_event_source, priority);
2633                 if (r < 0)
2634                         goto fail;
2635         }
2636
2637         r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
2638         if (r < 0)
2639                 goto fail;
2640
2641         r = sd_event_add_monotonic(bus->event, 0, 0, time_callback, bus, &bus->time_event_source);
2642         if (r < 0)
2643                 goto fail;
2644
2645         r = sd_event_source_set_priority(bus->time_event_source, priority);
2646         if (r < 0)
2647                 goto fail;
2648
2649         r = sd_event_add_exit(bus->event, quit_callback, bus, &bus->quit_event_source);
2650         if (r < 0)
2651                 goto fail;
2652
2653         return 0;
2654
2655 fail:
2656         sd_bus_detach_event(bus);
2657         return r;
2658 }
2659
2660 _public_ int sd_bus_detach_event(sd_bus *bus) {
2661         assert_return(bus, -EINVAL);
2662
2663         if (!bus->event)
2664                 return 0;
2665
2666         if (bus->input_io_event_source) {
2667                 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
2668                 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
2669         }
2670
2671         if (bus->output_io_event_source) {
2672                 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
2673                 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
2674         }
2675
2676         if (bus->time_event_source) {
2677                 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
2678                 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
2679         }
2680
2681         if (bus->quit_event_source) {
2682                 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
2683                 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
2684         }
2685
2686         if (bus->event)
2687                 bus->event = sd_event_unref(bus->event);
2688
2689         return 1;
2690 }
2691
2692 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
2693         assert_return(bus, NULL);
2694
2695         return bus->event;
2696 }
2697
2698 _public_ sd_bus_message* sd_bus_get_current(sd_bus *bus) {
2699         assert_return(bus, NULL);
2700
2701         return bus->current;
2702 }
2703
2704 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
2705         sd_bus *b = NULL;
2706         int r;
2707
2708         assert(bus_open);
2709         assert(default_bus);
2710
2711         if (!ret)
2712                 return !!*default_bus;
2713
2714         if (*default_bus) {
2715                 *ret = sd_bus_ref(*default_bus);
2716                 return 0;
2717         }
2718
2719         r = bus_open(&b);
2720         if (r < 0)
2721                 return r;
2722
2723         b->default_bus_ptr = default_bus;
2724         b->tid = gettid();
2725         *default_bus = b;
2726
2727         *ret = b;
2728         return 1;
2729 }
2730
2731 _public_ int sd_bus_default_system(sd_bus **ret) {
2732         static __thread sd_bus *default_system_bus = NULL;
2733
2734         return bus_default(sd_bus_open_system, &default_system_bus, ret);
2735 }
2736
2737 _public_ int sd_bus_default_user(sd_bus **ret) {
2738         static __thread sd_bus *default_user_bus = NULL;
2739
2740         return bus_default(sd_bus_open_user, &default_user_bus, ret);
2741 }
2742
2743 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
2744         assert_return(b, -EINVAL);
2745         assert_return(tid, -EINVAL);
2746         assert_return(!bus_pid_changed(b), -ECHILD);
2747
2748         if (b->tid != 0) {
2749                 *tid = b->tid;
2750                 return 0;
2751         }
2752
2753         if (b->event)
2754                 return sd_event_get_tid(b->event, tid);
2755
2756         return -ENXIO;
2757 }
2758
2759 _public_ char *sd_bus_label_escape(const char *s) {
2760         char *r, *t;
2761         const char *f;
2762
2763         assert_return(s, NULL);
2764
2765         /* Escapes all chars that D-Bus' object path cannot deal
2766          * with. Can be reversed with bus_path_unescape(). We special
2767          * case the empty string. */
2768
2769         if (*s == 0)
2770                 return strdup("_");
2771
2772         r = new(char, strlen(s)*3 + 1);
2773         if (!r)
2774                 return NULL;
2775
2776         for (f = s, t = r; *f; f++) {
2777
2778                 /* Escape everything that is not a-zA-Z0-9. We also
2779                  * escape 0-9 if it's the first character */
2780
2781                 if (!(*f >= 'A' && *f <= 'Z') &&
2782                     !(*f >= 'a' && *f <= 'z') &&
2783                     !(f > s && *f >= '0' && *f <= '9')) {
2784                         *(t++) = '_';
2785                         *(t++) = hexchar(*f >> 4);
2786                         *(t++) = hexchar(*f);
2787                 } else
2788                         *(t++) = *f;
2789         }
2790
2791         *t = 0;
2792
2793         return r;
2794 }
2795
2796 _public_ char *sd_bus_label_unescape(const char *f) {
2797         char *r, *t;
2798
2799         assert_return(f, NULL);
2800
2801         /* Special case for the empty string */
2802         if (streq(f, "_"))
2803                 return strdup("");
2804
2805         r = new(char, strlen(f) + 1);
2806         if (!r)
2807                 return NULL;
2808
2809         for (t = r; *f; f++) {
2810
2811                 if (*f == '_') {
2812                         int a, b;
2813
2814                         if ((a = unhexchar(f[1])) < 0 ||
2815                             (b = unhexchar(f[2])) < 0) {
2816                                 /* Invalid escape code, let's take it literal then */
2817                                 *(t++) = '_';
2818                         } else {
2819                                 *(t++) = (char) ((a << 4) | b);
2820                                 f += 2;
2821                         }
2822                 } else
2823                         *(t++) = *f;
2824         }
2825
2826         *t = 0;
2827
2828         return r;
2829 }
2830
2831 _public_ int sd_bus_get_peer_creds(sd_bus *bus, uint64_t mask, sd_bus_creds **ret) {
2832         sd_bus_creds *c;
2833         pid_t pid = 0;
2834         int r;
2835
2836         assert_return(bus, -EINVAL);
2837         assert_return(mask <= _SD_BUS_CREDS_ALL, -ENOTSUP);
2838         assert_return(ret, -EINVAL);
2839         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2840         assert_return(!bus_pid_changed(bus), -ECHILD);
2841         assert_return(!bus->is_kernel, -ENOTSUP);
2842
2843         if (!bus->ucred_valid && !isempty(bus->label))
2844                 return -ENODATA;
2845
2846         c = bus_creds_new();
2847         if (!c)
2848                 return -ENOMEM;
2849
2850         if (bus->ucred_valid) {
2851                 pid = c->pid = bus->ucred.pid;
2852                 c->uid = bus->ucred.uid;
2853                 c->gid = bus->ucred.gid;
2854
2855                 c->mask |= (SD_BUS_CREDS_UID | SD_BUS_CREDS_PID | SD_BUS_CREDS_GID) & mask;
2856         }
2857
2858         if (!isempty(bus->label) && (mask & SD_BUS_CREDS_SELINUX_CONTEXT)) {
2859                 c->label = strdup(bus->label);
2860                 if (!c->label) {
2861                         sd_bus_creds_unref(c);
2862                         return -ENOMEM;
2863                 }
2864
2865                 c->mask |= SD_BUS_CREDS_SELINUX_CONTEXT;
2866         }
2867
2868         r = bus_creds_add_more(c, mask, pid, 0);
2869         if (r < 0)
2870                 return r;
2871
2872         *ret = c;
2873         return 0;
2874 }