chiark / gitweb /
bus: properly handle message bodies that are a chain of memory areas rather than...
[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
30 #include "util.h"
31 #include "macro.h"
32 #include "strv.h"
33 #include "set.h"
34 #include "missing.h"
35
36 #include "sd-bus.h"
37 #include "bus-internal.h"
38 #include "bus-message.h"
39 #include "bus-type.h"
40 #include "bus-socket.h"
41 #include "bus-kernel.h"
42 #include "bus-control.h"
43
44 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec);
45
46 static void bus_free(sd_bus *b) {
47         struct filter_callback *f;
48         struct object_callback *c;
49         unsigned i;
50
51         assert(b);
52
53         sd_bus_close(b);
54
55         free(b->rbuffer);
56         free(b->unique_name);
57         free(b->auth_buffer);
58         free(b->address);
59         free(b->kernel);
60
61         free(b->exec_path);
62         strv_free(b->exec_argv);
63
64         close_many(b->fds, b->n_fds);
65         free(b->fds);
66
67         for (i = 0; i < b->rqueue_size; i++)
68                 sd_bus_message_unref(b->rqueue[i]);
69         free(b->rqueue);
70
71         for (i = 0; i < b->wqueue_size; i++)
72                 sd_bus_message_unref(b->wqueue[i]);
73         free(b->wqueue);
74
75         hashmap_free_free(b->reply_callbacks);
76         prioq_free(b->reply_callbacks_prioq);
77
78         while ((f = b->filter_callbacks)) {
79                 LIST_REMOVE(struct filter_callback, callbacks, b->filter_callbacks, f);
80                 free(f);
81         }
82
83         while ((c = hashmap_steal_first(b->object_callbacks))) {
84                 free(c->path);
85                 free(c);
86         }
87
88         hashmap_free(b->object_callbacks);
89         bus_match_free(&b->match_callbacks);
90
91         bus_kernel_flush_memfd(b);
92
93         free(b);
94 }
95
96 int sd_bus_new(sd_bus **ret) {
97         sd_bus *r;
98
99         if (!ret)
100                 return -EINVAL;
101
102         r = new0(sd_bus, 1);
103         if (!r)
104                 return -ENOMEM;
105
106         r->n_ref = 1;
107         r->input_fd = r->output_fd = -1;
108         r->message_version = 1;
109         r->negotiate_fds = true;
110
111         /* We guarantee that wqueue always has space for at least one
112          * entry */
113         r->wqueue = new(sd_bus_message*, 1);
114         if (!r->wqueue) {
115                 free(r);
116                 return -ENOMEM;
117         }
118
119         *ret = r;
120         return 0;
121 }
122
123 int sd_bus_set_address(sd_bus *bus, const char *address) {
124         char *a;
125
126         if (!bus)
127                 return -EINVAL;
128         if (bus->state != BUS_UNSET)
129                 return -EPERM;
130         if (!address)
131                 return -EINVAL;
132
133         a = strdup(address);
134         if (!a)
135                 return -ENOMEM;
136
137         free(bus->address);
138         bus->address = a;
139
140         return 0;
141 }
142
143 int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd) {
144         if (!bus)
145                 return -EINVAL;
146         if (bus->state != BUS_UNSET)
147                 return -EPERM;
148         if (input_fd < 0)
149                 return -EINVAL;
150         if (output_fd < 0)
151                 return -EINVAL;
152
153         bus->input_fd = input_fd;
154         bus->output_fd = output_fd;
155         return 0;
156 }
157
158 int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]) {
159         char *p, **a;
160
161         if (!bus)
162                 return -EINVAL;
163         if (bus->state != BUS_UNSET)
164                 return -EPERM;
165         if (!path)
166                 return -EINVAL;
167         if (strv_isempty(argv))
168                 return -EINVAL;
169
170         p = strdup(path);
171         if (!p)
172                 return -ENOMEM;
173
174         a = strv_copy(argv);
175         if (!a) {
176                 free(p);
177                 return -ENOMEM;
178         }
179
180         free(bus->exec_path);
181         strv_free(bus->exec_argv);
182
183         bus->exec_path = p;
184         bus->exec_argv = a;
185
186         return 0;
187 }
188
189 int sd_bus_set_bus_client(sd_bus *bus, int b) {
190         if (!bus)
191                 return -EINVAL;
192         if (bus->state != BUS_UNSET)
193                 return -EPERM;
194
195         bus->bus_client = !!b;
196         return 0;
197 }
198
199 int sd_bus_set_negotiate_fds(sd_bus *bus, int b) {
200         if (!bus)
201                 return -EINVAL;
202         if (bus->state != BUS_UNSET)
203                 return -EPERM;
204
205         bus->negotiate_fds = !!b;
206         return 0;
207 }
208
209 int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id) {
210         if (!bus)
211                 return -EINVAL;
212         if (!b && !sd_id128_equal(server_id, SD_ID128_NULL))
213                 return -EINVAL;
214         if (bus->state != BUS_UNSET)
215                 return -EPERM;
216
217         bus->is_server = !!b;
218         bus->server_id = server_id;
219         return 0;
220 }
221
222 int sd_bus_set_anonymous(sd_bus *bus, int b) {
223         if (!bus)
224                 return -EINVAL;
225         if (bus->state != BUS_UNSET)
226                 return -EPERM;
227
228         bus->anonymous_auth = !!b;
229         return 0;
230 }
231
232 static int hello_callback(sd_bus *bus, int error, sd_bus_message *reply, void *userdata) {
233         const char *s;
234         int r;
235
236         assert(bus);
237         assert(bus->state == BUS_HELLO);
238
239         if (error != 0)
240                 return -error;
241
242         assert(reply);
243
244         r = sd_bus_message_read(reply, "s", &s);
245         if (r < 0)
246                 return r;
247
248         if (!service_name_is_valid(s) || s[0] != ':')
249                 return -EBADMSG;
250
251         bus->unique_name = strdup(s);
252         if (!bus->unique_name)
253                 return -ENOMEM;
254
255         bus->state = BUS_RUNNING;
256
257         return 1;
258 }
259
260 static int bus_send_hello(sd_bus *bus) {
261         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
262         int r;
263
264         assert(bus);
265
266         if (!bus->bus_client || bus->is_kernel)
267                 return 0;
268
269         r = sd_bus_message_new_method_call(
270                         bus,
271                         "org.freedesktop.DBus",
272                         "/",
273                         "org.freedesktop.DBus",
274                         "Hello",
275                         &m);
276         if (r < 0)
277                 return r;
278
279         return sd_bus_send_with_reply(bus, m, hello_callback, NULL, 0, &bus->hello_serial);
280 }
281
282 int bus_start_running(sd_bus *bus) {
283         assert(bus);
284
285         if (bus->bus_client && !bus->is_kernel) {
286                 bus->state = BUS_HELLO;
287                 return 1;
288         }
289
290         bus->state = BUS_RUNNING;
291         return 1;
292 }
293
294 static int parse_address_key(const char **p, const char *key, char **value) {
295         size_t l, n = 0;
296         const char *a;
297         char *r = NULL;
298
299         assert(p);
300         assert(*p);
301         assert(value);
302
303         if (key) {
304                 l = strlen(key);
305                 if (strncmp(*p, key, l) != 0)
306                         return 0;
307
308                 if ((*p)[l] != '=')
309                         return 0;
310
311                 if (*value)
312                         return -EINVAL;
313
314                 a = *p + l + 1;
315         } else
316                 a = *p;
317
318         while (*a != ';' && *a != ',' && *a != 0) {
319                 char c, *t;
320
321                 if (*a == '%') {
322                         int x, y;
323
324                         x = unhexchar(a[1]);
325                         if (x < 0) {
326                                 free(r);
327                                 return x;
328                         }
329
330                         y = unhexchar(a[2]);
331                         if (y < 0) {
332                                 free(r);
333                                 return y;
334                         }
335
336                         c = (char) ((x << 4) | y);
337                         a += 3;
338                 } else {
339                         c = *a;
340                         a++;
341                 }
342
343                 t = realloc(r, n + 2);
344                 if (!t) {
345                         free(r);
346                         return -ENOMEM;
347                 }
348
349                 r = t;
350                 r[n++] = c;
351         }
352
353         if (!r) {
354                 r = strdup("");
355                 if (!r)
356                         return -ENOMEM;
357         } else
358                 r[n] = 0;
359
360         if (*a == ',')
361                 a++;
362
363         *p = a;
364
365         free(*value);
366         *value = r;
367
368         return 1;
369 }
370
371 static void skip_address_key(const char **p) {
372         assert(p);
373         assert(*p);
374
375         *p += strcspn(*p, ",");
376
377         if (**p == ',')
378                 (*p) ++;
379 }
380
381 static int parse_unix_address(sd_bus *b, const char **p, char **guid) {
382         _cleanup_free_ char *path = NULL, *abstract = NULL;
383         size_t l;
384         int r;
385
386         assert(b);
387         assert(p);
388         assert(*p);
389         assert(guid);
390
391         while (**p != 0 && **p != ';') {
392                 r = parse_address_key(p, "guid", guid);
393                 if (r < 0)
394                         return r;
395                 else if (r > 0)
396                         continue;
397
398                 r = parse_address_key(p, "path", &path);
399                 if (r < 0)
400                         return r;
401                 else if (r > 0)
402                         continue;
403
404                 r = parse_address_key(p, "abstract", &abstract);
405                 if (r < 0)
406                         return r;
407                 else if (r > 0)
408                         continue;
409
410                 skip_address_key(p);
411         }
412
413         if (!path && !abstract)
414                 return -EINVAL;
415
416         if (path && abstract)
417                 return -EINVAL;
418
419         if (path) {
420                 l = strlen(path);
421                 if (l > sizeof(b->sockaddr.un.sun_path))
422                         return -E2BIG;
423
424                 b->sockaddr.un.sun_family = AF_UNIX;
425                 strncpy(b->sockaddr.un.sun_path, path, sizeof(b->sockaddr.un.sun_path));
426                 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l;
427         } else if (abstract) {
428                 l = strlen(abstract);
429                 if (l > sizeof(b->sockaddr.un.sun_path) - 1)
430                         return -E2BIG;
431
432                 b->sockaddr.un.sun_family = AF_UNIX;
433                 b->sockaddr.un.sun_path[0] = 0;
434                 strncpy(b->sockaddr.un.sun_path+1, abstract, sizeof(b->sockaddr.un.sun_path)-1);
435                 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
436         }
437
438         return 0;
439 }
440
441 static int parse_tcp_address(sd_bus *b, const char **p, char **guid) {
442         _cleanup_free_ char *host = NULL, *port = NULL, *family = NULL;
443         int r;
444         struct addrinfo *result, hints = {
445                 .ai_socktype = SOCK_STREAM,
446                 .ai_flags = AI_ADDRCONFIG,
447         };
448
449         assert(b);
450         assert(p);
451         assert(*p);
452         assert(guid);
453
454         while (**p != 0 && **p != ';') {
455                 r = parse_address_key(p, "guid", guid);
456                 if (r < 0)
457                         return r;
458                 else if (r > 0)
459                         continue;
460
461                 r = parse_address_key(p, "host", &host);
462                 if (r < 0)
463                         return r;
464                 else if (r > 0)
465                         continue;
466
467                 r = parse_address_key(p, "port", &port);
468                 if (r < 0)
469                         return r;
470                 else if (r > 0)
471                         continue;
472
473                 r = parse_address_key(p, "family", &family);
474                 if (r < 0)
475                         return r;
476                 else if (r > 0)
477                         continue;
478
479                 skip_address_key(p);
480         }
481
482         if (!host || !port)
483                 return -EINVAL;
484
485         if (family) {
486                 if (streq(family, "ipv4"))
487                         hints.ai_family = AF_INET;
488                 else if (streq(family, "ipv6"))
489                         hints.ai_family = AF_INET6;
490                 else
491                         return -EINVAL;
492         }
493
494         r = getaddrinfo(host, port, &hints, &result);
495         if (r == EAI_SYSTEM)
496                 return -errno;
497         else if (r != 0)
498                 return -EADDRNOTAVAIL;
499
500         memcpy(&b->sockaddr, result->ai_addr, result->ai_addrlen);
501         b->sockaddr_size = result->ai_addrlen;
502
503         freeaddrinfo(result);
504
505         return 0;
506 }
507
508 static int parse_exec_address(sd_bus *b, const char **p, char **guid) {
509         char *path = NULL;
510         unsigned n_argv = 0, j;
511         char **argv = NULL;
512         int r;
513
514         assert(b);
515         assert(p);
516         assert(*p);
517         assert(guid);
518
519         while (**p != 0 && **p != ';') {
520                 r = parse_address_key(p, "guid", guid);
521                 if (r < 0)
522                         goto fail;
523                 else if (r > 0)
524                         continue;
525
526                 r = parse_address_key(p, "path", &path);
527                 if (r < 0)
528                         goto fail;
529                 else if (r > 0)
530                         continue;
531
532                 if (startswith(*p, "argv")) {
533                         unsigned ul;
534
535                         errno = 0;
536                         ul = strtoul(*p + 4, (char**) p, 10);
537                         if (errno > 0 || **p != '=' || ul > 256) {
538                                 r = -EINVAL;
539                                 goto fail;
540                         }
541
542                         (*p) ++;
543
544                         if (ul >= n_argv) {
545                                 char **x;
546
547                                 x = realloc(argv, sizeof(char*) * (ul + 2));
548                                 if (!x) {
549                                         r = -ENOMEM;
550                                         goto fail;
551                                 }
552
553                                 memset(x + n_argv, 0, sizeof(char*) * (ul - n_argv + 2));
554
555                                 argv = x;
556                                 n_argv = ul + 1;
557                         }
558
559                         r = parse_address_key(p, NULL, argv + ul);
560                         if (r < 0)
561                                 goto fail;
562
563                         continue;
564                 }
565
566                 skip_address_key(p);
567         }
568
569         if (!path) {
570                 r = -EINVAL;
571                 goto fail;
572         }
573
574         /* Make sure there are no holes in the array, with the
575          * exception of argv[0] */
576         for (j = 1; j < n_argv; j++)
577                 if (!argv[j]) {
578                         r = -EINVAL;
579                         goto fail;
580                 }
581
582         if (argv && argv[0] == NULL) {
583                 argv[0] = strdup(path);
584                 if (!argv[0]) {
585                         r = -ENOMEM;
586                         goto fail;
587                 }
588         }
589
590         b->exec_path = path;
591         b->exec_argv = argv;
592         return 0;
593
594 fail:
595         for (j = 0; j < n_argv; j++)
596                 free(argv[j]);
597
598         free(argv);
599         free(path);
600         return r;
601 }
602
603 static int parse_kernel_address(sd_bus *b, const char **p, char **guid) {
604         _cleanup_free_ char *path = NULL;
605         int r;
606
607         assert(b);
608         assert(p);
609         assert(*p);
610         assert(guid);
611
612         while (**p != 0 && **p != ';') {
613                 r = parse_address_key(p, "guid", guid);
614                 if (r < 0)
615                         return r;
616                 else if (r > 0)
617                         continue;
618
619                 r = parse_address_key(p, "path", &path);
620                 if (r < 0)
621                         return r;
622                 else if (r > 0)
623                         continue;
624
625                 skip_address_key(p);
626         }
627
628         if (!path)
629                 return -EINVAL;
630
631         free(b->kernel);
632         b->kernel = path;
633         path = NULL;
634
635         return 0;
636 }
637
638 static void bus_reset_parsed_address(sd_bus *b) {
639         assert(b);
640
641         zero(b->sockaddr);
642         b->sockaddr_size = 0;
643         strv_free(b->exec_argv);
644         free(b->exec_path);
645         b->exec_path = NULL;
646         b->exec_argv = NULL;
647         b->server_id = SD_ID128_NULL;
648         free(b->kernel);
649         b->kernel = NULL;
650 }
651
652 static int bus_parse_next_address(sd_bus *b) {
653         _cleanup_free_ char *guid = NULL;
654         const char *a;
655         int r;
656
657         assert(b);
658
659         if (!b->address)
660                 return 0;
661         if (b->address[b->address_index] == 0)
662                 return 0;
663
664         bus_reset_parsed_address(b);
665
666         a = b->address + b->address_index;
667
668         while (*a != 0) {
669
670                 if (*a == ';') {
671                         a++;
672                         continue;
673                 }
674
675                 if (startswith(a, "unix:")) {
676                         a += 5;
677
678                         r = parse_unix_address(b, &a, &guid);
679                         if (r < 0)
680                                 return r;
681                         break;
682
683                 } else if (startswith(a, "tcp:")) {
684
685                         a += 4;
686                         r = parse_tcp_address(b, &a, &guid);
687                         if (r < 0)
688                                 return r;
689
690                         break;
691
692                 } else if (startswith(a, "unixexec:")) {
693
694                         a += 9;
695                         r = parse_exec_address(b, &a, &guid);
696                         if (r < 0)
697                                 return r;
698
699                         break;
700
701                 } else if (startswith(a, "kernel:")) {
702
703                         a += 7;
704                         r = parse_kernel_address(b, &a, &guid);
705                         if (r < 0)
706                                 return r;
707
708                         break;
709                 }
710
711                 a = strchr(a, ';');
712                 if (!a)
713                         return 0;
714         }
715
716         if (guid) {
717                 r = sd_id128_from_string(guid, &b->server_id);
718                 if (r < 0)
719                         return r;
720         }
721
722         b->address_index = a - b->address;
723         return 1;
724 }
725
726 static int bus_start_address(sd_bus *b) {
727         int r;
728
729         assert(b);
730
731         for (;;) {
732                 sd_bus_close(b);
733
734                 if (b->sockaddr.sa.sa_family != AF_UNSPEC) {
735
736                         r = bus_socket_connect(b);
737                         if (r >= 0)
738                                 return r;
739
740                         b->last_connect_error = -r;
741
742                 } else if (b->exec_path) {
743
744                         r = bus_socket_exec(b);
745                         if (r >= 0)
746                                 return r;
747
748                         b->last_connect_error = -r;
749                 } else if (b->kernel) {
750
751                         r = bus_kernel_connect(b);
752                         if (r >= 0)
753                                 return r;
754
755                         b->last_connect_error = -r;
756                 }
757
758                 r = bus_parse_next_address(b);
759                 if (r < 0)
760                         return r;
761                 if (r == 0)
762                         return b->last_connect_error ? -b->last_connect_error : -ECONNREFUSED;
763         }
764 }
765
766 int bus_next_address(sd_bus *b) {
767         assert(b);
768
769         bus_reset_parsed_address(b);
770         return bus_start_address(b);
771 }
772
773 static int bus_start_fd(sd_bus *b) {
774         struct stat st;
775         int r;
776
777         assert(b);
778         assert(b->input_fd >= 0);
779         assert(b->output_fd >= 0);
780
781         r = fd_nonblock(b->input_fd, true);
782         if (r < 0)
783                 return r;
784
785         r = fd_cloexec(b->input_fd, true);
786         if (r < 0)
787                 return r;
788
789         if (b->input_fd != b->output_fd) {
790                 r = fd_nonblock(b->output_fd, true);
791                 if (r < 0)
792                         return r;
793
794                 r = fd_cloexec(b->output_fd, true);
795                 if (r < 0)
796                         return r;
797         }
798
799         if (fstat(b->input_fd, &st) < 0)
800                 return -errno;
801
802         if (S_ISCHR(b->input_fd))
803                 return bus_kernel_take_fd(b);
804         else
805                 return bus_socket_take_fd(b);
806 }
807
808 int sd_bus_start(sd_bus *bus) {
809         int r;
810
811         if (!bus)
812                 return -EINVAL;
813         if (bus->state != BUS_UNSET)
814                 return -EPERM;
815
816         bus->state = BUS_OPENING;
817
818         if (bus->is_server && bus->bus_client)
819                 return -EINVAL;
820
821         if (bus->input_fd >= 0)
822                 r = bus_start_fd(bus);
823         else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->kernel)
824                 r = bus_start_address(bus);
825         else
826                 return -EINVAL;
827
828         if (r < 0)
829                 return r;
830
831         return bus_send_hello(bus);
832 }
833
834 int sd_bus_open_system(sd_bus **ret) {
835         const char *e;
836         sd_bus *b;
837         int r;
838
839         if (!ret)
840                 return -EINVAL;
841
842         r = sd_bus_new(&b);
843         if (r < 0)
844                 return r;
845
846         e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
847         if (e) {
848                 r = sd_bus_set_address(b, e);
849                 if (r < 0)
850                         goto fail;
851         } else {
852                 b->sockaddr.un.sun_family = AF_UNIX;
853                 strncpy(b->sockaddr.un.sun_path, "/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
854                 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + sizeof("/run/dbus/system_bus_socket") - 1;
855         }
856
857         b->bus_client = true;
858
859         r = sd_bus_start(b);
860         if (r < 0)
861                 goto fail;
862
863         *ret = b;
864         return 0;
865
866 fail:
867         bus_free(b);
868         return r;
869 }
870
871 int sd_bus_open_user(sd_bus **ret) {
872         const char *e;
873         sd_bus *b;
874         size_t l;
875         int r;
876
877         if (!ret)
878                 return -EINVAL;
879
880         r = sd_bus_new(&b);
881         if (r < 0)
882                 return r;
883
884         e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
885         if (e) {
886                 r = sd_bus_set_address(b, e);
887                 if (r < 0)
888                         goto fail;
889         } else {
890                 e = secure_getenv("XDG_RUNTIME_DIR");
891                 if (!e) {
892                         r = -ENOENT;
893                         goto fail;
894                 }
895
896                 l = strlen(e);
897                 if (l + 4 > sizeof(b->sockaddr.un.sun_path)) {
898                         r = -E2BIG;
899                         goto fail;
900                 }
901
902                 b->sockaddr.un.sun_family = AF_UNIX;
903                 memcpy(mempcpy(b->sockaddr.un.sun_path, e, l), "/bus", 4);
904                 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l + 4;
905         }
906
907         b->bus_client = true;
908
909         r = sd_bus_start(b);
910         if (r < 0)
911                 goto fail;
912
913         *ret = b;
914         return 0;
915
916 fail:
917         bus_free(b);
918         return r;
919 }
920
921 void sd_bus_close(sd_bus *bus) {
922         if (!bus)
923                 return;
924
925         if (bus->input_fd >= 0)
926                 close_nointr_nofail(bus->input_fd);
927         if (bus->output_fd >= 0 && bus->output_fd != bus->input_fd)
928                 close_nointr_nofail(bus->output_fd);
929
930         bus->input_fd = bus->output_fd = -1;
931 }
932
933 sd_bus *sd_bus_ref(sd_bus *bus) {
934         if (!bus)
935                 return NULL;
936
937         assert(bus->n_ref > 0);
938
939         bus->n_ref++;
940         return bus;
941 }
942
943 sd_bus *sd_bus_unref(sd_bus *bus) {
944         if (!bus)
945                 return NULL;
946
947         assert(bus->n_ref > 0);
948         bus->n_ref--;
949
950         if (bus->n_ref <= 0)
951                 bus_free(bus);
952
953         return NULL;
954 }
955
956 int sd_bus_is_open(sd_bus *bus) {
957         if (!bus)
958                 return -EINVAL;
959
960         return bus->state != BUS_UNSET && bus->input_fd >= 0;
961 }
962
963 int sd_bus_can_send(sd_bus *bus, char type) {
964         int r;
965
966         if (!bus)
967                 return -EINVAL;
968         if (bus->output_fd < 0)
969                 return -ENOTCONN;
970
971         if (type == SD_BUS_TYPE_UNIX_FD) {
972                 if (!bus->negotiate_fds)
973                         return 0;
974
975                 r = bus_ensure_running(bus);
976                 if (r < 0)
977                         return r;
978
979                 return bus->can_fds;
980         }
981
982         return bus_type_is_valid(type);
983 }
984
985 int sd_bus_get_server_id(sd_bus *bus, sd_id128_t *server_id) {
986         int r;
987
988         if (!bus)
989                 return -EINVAL;
990         if (!server_id)
991                 return -EINVAL;
992
993         r = bus_ensure_running(bus);
994         if (r < 0)
995                 return r;
996
997         *server_id = bus->server_id;
998         return 0;
999 }
1000
1001 static int bus_seal_message(sd_bus *b, sd_bus_message *m) {
1002         assert(m);
1003
1004         if (m->header->version > b->message_version)
1005                 return -EPERM;
1006
1007         if (m->sealed)
1008                 return 0;
1009
1010         return bus_message_seal(m, ++b->serial);
1011 }
1012
1013 static int dispatch_wqueue(sd_bus *bus) {
1014         int r, ret = 0;
1015
1016         assert(bus);
1017         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1018
1019         if (bus->output_fd < 0)
1020                 return -ENOTCONN;
1021
1022         while (bus->wqueue_size > 0) {
1023
1024                 if (bus->is_kernel)
1025                         r = bus_kernel_write_message(bus, bus->wqueue[0]);
1026                 else
1027                         r = bus_socket_write_message(bus, bus->wqueue[0], &bus->windex);
1028
1029                 if (r < 0) {
1030                         sd_bus_close(bus);
1031                         return r;
1032                 } else if (r == 0)
1033                         /* Didn't do anything this time */
1034                         return ret;
1035                 else if (bus->is_kernel || bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
1036                         /* Fully written. Let's drop the entry from
1037                          * the queue.
1038                          *
1039                          * This isn't particularly optimized, but
1040                          * well, this is supposed to be our worst-case
1041                          * buffer only, and the socket buffer is
1042                          * supposed to be our primary buffer, and if
1043                          * it got full, then all bets are off
1044                          * anyway. */
1045
1046                         sd_bus_message_unref(bus->wqueue[0]);
1047                         bus->wqueue_size --;
1048                         memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
1049                         bus->windex = 0;
1050
1051                         ret = 1;
1052                 }
1053         }
1054
1055         return ret;
1056 }
1057
1058 static int dispatch_rqueue(sd_bus *bus, sd_bus_message **m) {
1059         sd_bus_message *z = NULL;
1060         int r, ret = 0;
1061
1062         assert(bus);
1063         assert(m);
1064         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1065
1066         if (bus->input_fd < 0)
1067                 return -ENOTCONN;
1068
1069         if (bus->rqueue_size > 0) {
1070                 /* Dispatch a queued message */
1071
1072                 *m = bus->rqueue[0];
1073                 bus->rqueue_size --;
1074                 memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
1075                 return 1;
1076         }
1077
1078         /* Try to read a new message */
1079         do {
1080                 if (bus->is_kernel)
1081                         r = bus_kernel_read_message(bus, &z);
1082                 else
1083                         r = bus_socket_read_message(bus, &z);
1084
1085                 if (r < 0) {
1086                         sd_bus_close(bus);
1087                         return r;
1088                 }
1089                 if (r == 0)
1090                         return ret;
1091
1092                 r = 1;
1093         } while (!z);
1094
1095         *m = z;
1096         return 1;
1097 }
1098
1099 int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *serial) {
1100         int r;
1101
1102         if (!bus)
1103                 return -EINVAL;
1104         if (bus->state == BUS_UNSET)
1105                 return -ENOTCONN;
1106         if (bus->output_fd < 0)
1107                 return -ENOTCONN;
1108         if (!m)
1109                 return -EINVAL;
1110
1111         if (m->n_fds > 0) {
1112                 r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
1113                 if (r < 0)
1114                         return r;
1115                 if (r == 0)
1116                         return -ENOTSUP;
1117         }
1118
1119         /* If the serial number isn't kept, then we know that no reply
1120          * is expected */
1121         if (!serial && !m->sealed)
1122                 m->header->flags |= SD_BUS_MESSAGE_NO_REPLY_EXPECTED;
1123
1124         r = bus_seal_message(bus, m);
1125         if (r < 0)
1126                 return r;
1127
1128         /* If this is a reply and no reply was requested, then let's
1129          * suppress this, if we can */
1130         if (m->dont_send && !serial)
1131                 return 0;
1132
1133         if ((bus->state == BUS_RUNNING || bus->state == BUS_HELLO) && bus->wqueue_size <= 0) {
1134                 size_t idx = 0;
1135
1136                 if (bus->is_kernel)
1137                         r = bus_kernel_write_message(bus, m);
1138                 else
1139                         r = bus_socket_write_message(bus, m, &idx);
1140
1141                 if (r < 0) {
1142                         sd_bus_close(bus);
1143                         return r;
1144                 } else if (!bus->is_kernel && idx < BUS_MESSAGE_SIZE(m))  {
1145                         /* Wasn't fully written. So let's remember how
1146                          * much was written. Note that the first entry
1147                          * of the wqueue array is always allocated so
1148                          * that we always can remember how much was
1149                          * written. */
1150                         bus->wqueue[0] = sd_bus_message_ref(m);
1151                         bus->wqueue_size = 1;
1152                         bus->windex = idx;
1153                 }
1154         } else {
1155                 sd_bus_message **q;
1156
1157                 /* Just append it to the queue. */
1158
1159                 if (bus->wqueue_size >= BUS_WQUEUE_MAX)
1160                         return -ENOBUFS;
1161
1162                 q = realloc(bus->wqueue, sizeof(sd_bus_message*) * (bus->wqueue_size + 1));
1163                 if (!q)
1164                         return -ENOMEM;
1165
1166                 bus->wqueue = q;
1167                 q[bus->wqueue_size ++] = sd_bus_message_ref(m);
1168         }
1169
1170         if (serial)
1171                 *serial = BUS_MESSAGE_SERIAL(m);
1172
1173         return 0;
1174 }
1175
1176 static usec_t calc_elapse(uint64_t usec) {
1177         if (usec == (uint64_t) -1)
1178                 return 0;
1179
1180         if (usec == 0)
1181                 usec = BUS_DEFAULT_TIMEOUT;
1182
1183         return now(CLOCK_MONOTONIC) + usec;
1184 }
1185
1186 static int timeout_compare(const void *a, const void *b) {
1187         const struct reply_callback *x = a, *y = b;
1188
1189         if (x->timeout != 0 && y->timeout == 0)
1190                 return -1;
1191
1192         if (x->timeout == 0 && y->timeout != 0)
1193                 return 1;
1194
1195         if (x->timeout < y->timeout)
1196                 return -1;
1197
1198         if (x->timeout > y->timeout)
1199                 return 1;
1200
1201         return 0;
1202 }
1203
1204 int sd_bus_send_with_reply(
1205                 sd_bus *bus,
1206                 sd_bus_message *m,
1207                 sd_bus_message_handler_t callback,
1208                 void *userdata,
1209                 uint64_t usec,
1210                 uint64_t *serial) {
1211
1212         struct reply_callback *c;
1213         int r;
1214
1215         if (!bus)
1216                 return -EINVAL;
1217         if (bus->state == BUS_UNSET)
1218                 return -ENOTCONN;
1219         if (bus->output_fd < 0)
1220                 return -ENOTCONN;
1221         if (!m)
1222                 return -EINVAL;
1223         if (!callback)
1224                 return -EINVAL;
1225         if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
1226                 return -EINVAL;
1227         if (m->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED)
1228                 return -EINVAL;
1229
1230         r = hashmap_ensure_allocated(&bus->reply_callbacks, uint64_hash_func, uint64_compare_func);
1231         if (r < 0)
1232                 return r;
1233
1234         if (usec != (uint64_t) -1) {
1235                 r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
1236                 if (r < 0)
1237                         return r;
1238         }
1239
1240         r = bus_seal_message(bus, m);
1241         if (r < 0)
1242                 return r;
1243
1244         c = new0(struct reply_callback, 1);
1245         if (!c)
1246                 return -ENOMEM;
1247
1248         c->callback = callback;
1249         c->userdata = userdata;
1250         c->serial = BUS_MESSAGE_SERIAL(m);
1251         c->timeout = calc_elapse(usec);
1252
1253         r = hashmap_put(bus->reply_callbacks, &c->serial, c);
1254         if (r < 0) {
1255                 free(c);
1256                 return r;
1257         }
1258
1259         if (c->timeout != 0) {
1260                 r = prioq_put(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1261                 if (r < 0) {
1262                         c->timeout = 0;
1263                         sd_bus_send_with_reply_cancel(bus, c->serial);
1264                         return r;
1265                 }
1266         }
1267
1268         r = sd_bus_send(bus, m, serial);
1269         if (r < 0) {
1270                 sd_bus_send_with_reply_cancel(bus, c->serial);
1271                 return r;
1272         }
1273
1274         return r;
1275 }
1276
1277 int sd_bus_send_with_reply_cancel(sd_bus *bus, uint64_t serial) {
1278         struct reply_callback *c;
1279
1280         if (!bus)
1281                 return -EINVAL;
1282         if (serial == 0)
1283                 return -EINVAL;
1284
1285         c = hashmap_remove(bus->reply_callbacks, &serial);
1286         if (!c)
1287                 return 0;
1288
1289         if (c->timeout != 0)
1290                 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1291
1292         free(c);
1293         return 1;
1294 }
1295
1296 int bus_ensure_running(sd_bus *bus) {
1297         int r;
1298
1299         assert(bus);
1300
1301         if (bus->input_fd < 0)
1302                 return -ENOTCONN;
1303         if (bus->state == BUS_UNSET)
1304                 return -ENOTCONN;
1305
1306         if (bus->state == BUS_RUNNING)
1307                 return 1;
1308
1309         for (;;) {
1310                 r = sd_bus_process(bus, NULL);
1311                 if (r < 0)
1312                         return r;
1313                 if (bus->state == BUS_RUNNING)
1314                         return 1;
1315                 if (r > 0)
1316                         continue;
1317
1318                 r = sd_bus_wait(bus, (uint64_t) -1);
1319                 if (r < 0)
1320                         return r;
1321         }
1322 }
1323
1324 int sd_bus_send_with_reply_and_block(
1325                 sd_bus *bus,
1326                 sd_bus_message *m,
1327                 uint64_t usec,
1328                 sd_bus_error *error,
1329                 sd_bus_message **reply) {
1330
1331         int r;
1332         usec_t timeout;
1333         uint64_t serial;
1334         bool room = false;
1335
1336         if (!bus)
1337                 return -EINVAL;
1338         if (bus->output_fd < 0)
1339                 return -ENOTCONN;
1340         if (bus->state == BUS_UNSET)
1341                 return -ENOTCONN;
1342         if (!m)
1343                 return -EINVAL;
1344         if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
1345                 return -EINVAL;
1346         if (m->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED)
1347                 return -EINVAL;
1348         if (bus_error_is_dirty(error))
1349                 return -EINVAL;
1350
1351         r = bus_ensure_running(bus);
1352         if (r < 0)
1353                 return r;
1354
1355         r = sd_bus_send(bus, m, &serial);
1356         if (r < 0)
1357                 return r;
1358
1359         timeout = calc_elapse(usec);
1360
1361         for (;;) {
1362                 usec_t left;
1363                 sd_bus_message *incoming = NULL;
1364
1365                 if (!room) {
1366                         sd_bus_message **q;
1367
1368                         if (bus->rqueue_size >= BUS_RQUEUE_MAX)
1369                                 return -ENOBUFS;
1370
1371                         /* Make sure there's room for queuing this
1372                          * locally, before we read the message */
1373
1374                         q = realloc(bus->rqueue, (bus->rqueue_size + 1) * sizeof(sd_bus_message*));
1375                         if (!q)
1376                                 return -ENOMEM;
1377
1378                         bus->rqueue = q;
1379                         room = true;
1380                 }
1381
1382                 if (bus->is_kernel)
1383                         r = bus_kernel_read_message(bus, &incoming);
1384                 else
1385                         r = bus_socket_read_message(bus, &incoming);
1386                 if (r < 0)
1387                         return r;
1388                 if (incoming) {
1389
1390                         if (incoming->reply_serial == serial) {
1391                                 /* Found a match! */
1392
1393                                 if (incoming->header->type == SD_BUS_MESSAGE_TYPE_METHOD_RETURN) {
1394
1395                                         if (reply)
1396                                                 *reply = incoming;
1397                                         else
1398                                                 sd_bus_message_unref(incoming);
1399
1400                                         return 0;
1401                                 }
1402
1403                                 if (incoming->header->type == SD_BUS_MESSAGE_TYPE_METHOD_ERROR) {
1404                                         int k;
1405
1406                                         r = sd_bus_error_copy(error, &incoming->error);
1407                                         if (r < 0) {
1408                                                 sd_bus_message_unref(incoming);
1409                                                 return r;
1410                                         }
1411
1412                                         k = bus_error_to_errno(&incoming->error);
1413                                         sd_bus_message_unref(incoming);
1414                                         return k;
1415                                 }
1416
1417                                 sd_bus_message_unref(incoming);
1418                                 return -EIO;
1419                         }
1420
1421                         /* There's already guaranteed to be room for
1422                          * this, so need to resize things here */
1423                         bus->rqueue[bus->rqueue_size ++] = incoming;
1424                         room = false;
1425
1426                         /* Try to read more, right-away */
1427                         continue;
1428                 }
1429                 if (r != 0)
1430                         continue;
1431
1432                 if (timeout > 0) {
1433                         usec_t n;
1434
1435                         n = now(CLOCK_MONOTONIC);
1436                         if (n >= timeout)
1437                                 return -ETIMEDOUT;
1438
1439                         left = timeout - n;
1440                 } else
1441                         left = (uint64_t) -1;
1442
1443                 r = bus_poll(bus, true, left);
1444                 if (r < 0)
1445                         return r;
1446
1447                 r = dispatch_wqueue(bus);
1448                 if (r < 0)
1449                         return r;
1450         }
1451 }
1452
1453 int sd_bus_get_fd(sd_bus *bus) {
1454         if (!bus)
1455                 return -EINVAL;
1456         if (bus->input_fd < 0)
1457                 return -ENOTCONN;
1458         if (bus->input_fd != bus->output_fd)
1459                 return -EPERM;
1460
1461         return bus->input_fd;
1462 }
1463
1464 int sd_bus_get_events(sd_bus *bus) {
1465         int flags = 0;
1466
1467         if (!bus)
1468                 return -EINVAL;
1469         if (bus->state == BUS_UNSET)
1470                 return -ENOTCONN;
1471         if (bus->input_fd < 0)
1472                 return -ENOTCONN;
1473
1474         if (bus->state == BUS_OPENING)
1475                 flags |= POLLOUT;
1476         else if (bus->state == BUS_AUTHENTICATING) {
1477
1478                 if (bus_socket_auth_needs_write(bus))
1479                         flags |= POLLOUT;
1480
1481                 flags |= POLLIN;
1482
1483         } else if (bus->state == BUS_RUNNING || bus->state == BUS_HELLO) {
1484                 if (bus->rqueue_size <= 0)
1485                         flags |= POLLIN;
1486                 if (bus->wqueue_size > 0)
1487                         flags |= POLLOUT;
1488         }
1489
1490         return flags;
1491 }
1492
1493 int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
1494         struct reply_callback *c;
1495
1496         if (!bus)
1497                 return -EINVAL;
1498         if (!timeout_usec)
1499                 return -EINVAL;
1500         if (bus->state == BUS_UNSET)
1501                 return -ENOTCONN;
1502         if (bus->input_fd < 0)
1503                 return -ENOTCONN;
1504
1505         if (bus->state == BUS_AUTHENTICATING) {
1506                 *timeout_usec = bus->auth_timeout;
1507                 return 1;
1508         }
1509
1510         if (bus->state != BUS_RUNNING && bus->state != BUS_HELLO) {
1511                 *timeout_usec = (uint64_t) -1;
1512                 return 0;
1513         }
1514
1515         c = prioq_peek(bus->reply_callbacks_prioq);
1516         if (!c) {
1517                 *timeout_usec = (uint64_t) -1;
1518                 return 0;
1519         }
1520
1521         *timeout_usec = c->timeout;
1522         return 1;
1523 }
1524
1525 static int process_timeout(sd_bus *bus) {
1526         struct reply_callback *c;
1527         usec_t n;
1528         int r;
1529
1530         assert(bus);
1531
1532         c = prioq_peek(bus->reply_callbacks_prioq);
1533         if (!c)
1534                 return 0;
1535
1536         n = now(CLOCK_MONOTONIC);
1537         if (c->timeout > n)
1538                 return 0;
1539
1540         assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
1541         hashmap_remove(bus->reply_callbacks, &c->serial);
1542
1543         r = c->callback(bus, ETIMEDOUT, NULL, c->userdata);
1544         free(c);
1545
1546         return r < 0 ? r : 1;
1547 }
1548
1549 static int process_hello(sd_bus *bus, sd_bus_message *m) {
1550         assert(bus);
1551         assert(m);
1552
1553         if (bus->state != BUS_HELLO)
1554                 return 0;
1555
1556         /* Let's make sure the first message on the bus is the HELLO
1557          * reply. But note that we don't actually parse the message
1558          * here (we leave that to the usual handling), we just verify
1559          * we don't let any earlier msg through. */
1560
1561         if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_RETURN &&
1562             m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_ERROR)
1563                 return -EIO;
1564
1565         if (m->reply_serial != bus->hello_serial)
1566                 return -EIO;
1567
1568         return 0;
1569 }
1570
1571 static int process_reply(sd_bus *bus, sd_bus_message *m) {
1572         struct reply_callback *c;
1573         int r;
1574
1575         assert(bus);
1576         assert(m);
1577
1578         if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_RETURN &&
1579             m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_ERROR)
1580                 return 0;
1581
1582         c = hashmap_remove(bus->reply_callbacks, &m->reply_serial);
1583         if (!c)
1584                 return 0;
1585
1586         if (c->timeout != 0)
1587                 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1588
1589         r = sd_bus_message_rewind(m, true);
1590         if (r < 0)
1591                 return r;
1592
1593         r = c->callback(bus, 0, m, c->userdata);
1594         free(c);
1595
1596         return r;
1597 }
1598
1599 static int process_filter(sd_bus *bus, sd_bus_message *m) {
1600         struct filter_callback *l;
1601         int r;
1602
1603         assert(bus);
1604         assert(m);
1605
1606         do {
1607                 bus->filter_callbacks_modified = false;
1608
1609                 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
1610
1611                         if (bus->filter_callbacks_modified)
1612                                 break;
1613
1614                         /* Don't run this more than once per iteration */
1615                         if (l->last_iteration == bus->iteration_counter)
1616                                 continue;
1617
1618                         l->last_iteration = bus->iteration_counter;
1619
1620                         r = sd_bus_message_rewind(m, true);
1621                         if (r < 0)
1622                                 return r;
1623
1624                         r = l->callback(bus, 0, m, l->userdata);
1625                         if (r != 0)
1626                                 return r;
1627
1628                 }
1629
1630         } while (bus->filter_callbacks_modified);
1631
1632         return 0;
1633 }
1634
1635 static int process_match(sd_bus *bus, sd_bus_message *m) {
1636         int r;
1637
1638         assert(bus);
1639         assert(m);
1640
1641         do {
1642                 bus->match_callbacks_modified = false;
1643
1644                 r = bus_match_run(bus, &bus->match_callbacks, 0, m);
1645                 if (r != 0)
1646                         return r;
1647
1648         } while (bus->match_callbacks_modified);
1649
1650         return 0;
1651 }
1652
1653 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
1654         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1655         int r;
1656
1657         assert(bus);
1658         assert(m);
1659
1660         if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
1661                 return 0;
1662
1663         if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
1664                 return 0;
1665
1666         if (m->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED)
1667                 return 1;
1668
1669         if (streq_ptr(m->member, "Ping"))
1670                 r = sd_bus_message_new_method_return(bus, m, &reply);
1671         else if (streq_ptr(m->member, "GetMachineId")) {
1672                 sd_id128_t id;
1673                 char sid[33];
1674
1675                 r = sd_id128_get_machine(&id);
1676                 if (r < 0)
1677                         return r;
1678
1679                 r = sd_bus_message_new_method_return(bus, m, &reply);
1680                 if (r < 0)
1681                         return r;
1682
1683                 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
1684         } else {
1685                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1686
1687                 sd_bus_error_set(&error,
1688                                  "org.freedesktop.DBus.Error.UnknownMethod",
1689                                  "Unknown method '%s' on interface '%s'.", m->member, m->interface);
1690
1691                 r = sd_bus_message_new_method_error(bus, m, &error, &reply);
1692         }
1693
1694         if (r < 0)
1695                 return r;
1696
1697         r = sd_bus_send(bus, reply, NULL);
1698         if (r < 0)
1699                 return r;
1700
1701         return 1;
1702 }
1703
1704 static int process_object(sd_bus *bus, sd_bus_message *m) {
1705         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1706         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1707         struct object_callback *c;
1708         int r;
1709         bool found = false;
1710         size_t pl;
1711
1712         assert(bus);
1713         assert(m);
1714
1715         if (m->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
1716                 return 0;
1717
1718         if (hashmap_isempty(bus->object_callbacks))
1719                 return 0;
1720
1721         pl = strlen(m->path);
1722
1723         do {
1724                 char p[pl+1];
1725
1726                 bus->object_callbacks_modified = false;
1727
1728                 c = hashmap_get(bus->object_callbacks, m->path);
1729                 if (c && c->last_iteration != bus->iteration_counter) {
1730
1731                         c->last_iteration = bus->iteration_counter;
1732
1733                         r = sd_bus_message_rewind(m, true);
1734                         if (r < 0)
1735                                 return r;
1736
1737                         r = c->callback(bus, 0, m, c->userdata);
1738                         if (r != 0)
1739                                 return r;
1740
1741                         found = true;
1742                 }
1743
1744                 /* Look for fallback prefixes */
1745                 strcpy(p, m->path);
1746                 for (;;) {
1747                         char *e;
1748
1749                         if (bus->object_callbacks_modified)
1750                                 break;
1751
1752                         e = strrchr(p, '/');
1753                         if (e == p || !e)
1754                                 break;
1755
1756                         *e = 0;
1757
1758                         c = hashmap_get(bus->object_callbacks, p);
1759                         if (c && c->last_iteration != bus->iteration_counter && c->is_fallback) {
1760
1761                                 c->last_iteration = bus->iteration_counter;
1762
1763                                 r = sd_bus_message_rewind(m, true);
1764                                 if (r < 0)
1765                                         return r;
1766
1767                                 r = c->callback(bus, 0, m, c->userdata);
1768                                 if (r != 0)
1769                                         return r;
1770
1771                                 found = true;
1772                         }
1773                 }
1774
1775         } while (bus->object_callbacks_modified);
1776
1777         /* We found some handlers but none wanted to take this, then
1778          * return this -- with one exception, we can handle
1779          * introspection minimally ourselves */
1780         if (!found || sd_bus_message_is_method_call(m, "org.freedesktop.DBus.Introspectable", "Introspect"))
1781                 return 0;
1782
1783         sd_bus_error_set(&error,
1784                          "org.freedesktop.DBus.Error.UnknownMethod",
1785                          "Unknown method '%s' or interface '%s'.", m->member, m->interface);
1786
1787         r = sd_bus_message_new_method_error(bus, m, &error, &reply);
1788         if (r < 0)
1789                 return r;
1790
1791         r = sd_bus_send(bus, reply, NULL);
1792         if (r < 0)
1793                 return r;
1794
1795         return 1;
1796 }
1797
1798 static int process_introspect(sd_bus *bus, sd_bus_message *m) {
1799         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1800         _cleanup_free_ char *introspection = NULL;
1801         _cleanup_set_free_free_ Set *s = NULL;
1802         _cleanup_fclose_ FILE *f = NULL;
1803         struct object_callback *c;
1804         Iterator i;
1805         size_t size = 0;
1806         char *node;
1807         int r;
1808
1809         assert(bus);
1810         assert(m);
1811
1812         if (!sd_bus_message_is_method_call(m, "org.freedesktop.DBus.Introspectable", "Introspect"))
1813                 return 0;
1814
1815         if (!m->path)
1816                 return 0;
1817
1818         s = set_new(string_hash_func, string_compare_func);
1819         if (!s)
1820                 return -ENOMEM;
1821
1822         HASHMAP_FOREACH(c, bus->object_callbacks, i) {
1823                 const char *e;
1824                 char *a, *p;
1825
1826                 if (streq(c->path, "/"))
1827                         continue;
1828
1829                 if (streq(m->path, "/"))
1830                         e = c->path;
1831                 else {
1832                         e = startswith(c->path, m->path);
1833                         if (!e || *e != '/')
1834                                 continue;
1835                 }
1836
1837                 a = strdup(e+1);
1838                 if (!a)
1839                         return -ENOMEM;
1840
1841                 p = strchr(a, '/');
1842                 if (p)
1843                         *p = 0;
1844
1845                 r = set_consume(s, a);
1846                 if (r < 0 && r != -EEXIST)
1847                         return r;
1848         }
1849
1850         f = open_memstream(&introspection, &size);
1851         if (!f)
1852                 return -ENOMEM;
1853
1854         fputs(SD_BUS_INTROSPECT_DOCTYPE, f);
1855         fputs("<node>\n", f);
1856         fputs(SD_BUS_INTROSPECT_INTERFACE_PEER, f);
1857         fputs(SD_BUS_INTROSPECT_INTERFACE_INTROSPECTABLE, f);
1858
1859         while ((node = set_steal_first(s))) {
1860                 fprintf(f, " <node name=\"%s\"/>\n", node);
1861                 free(node);
1862         }
1863
1864         fputs("</node>\n", f);
1865
1866         fflush(f);
1867
1868         if (ferror(f))
1869                 return -ENOMEM;
1870
1871         r = sd_bus_message_new_method_return(bus, m, &reply);
1872         if (r < 0)
1873                 return r;
1874
1875         r = sd_bus_message_append(reply, "s", introspection);
1876         if (r < 0)
1877                 return r;
1878
1879         r = sd_bus_send(bus, reply, NULL);
1880         if (r < 0)
1881                 return r;
1882
1883         return 1;
1884 }
1885
1886 static int process_message(sd_bus *bus, sd_bus_message *m) {
1887         int r;
1888
1889         assert(bus);
1890         assert(m);
1891
1892         bus->iteration_counter++;
1893
1894         r = process_hello(bus, m);
1895         if (r != 0)
1896                 return r;
1897
1898         r = process_reply(bus, m);
1899         if (r != 0)
1900                 return r;
1901
1902         r = process_filter(bus, m);
1903         if (r != 0)
1904                 return r;
1905
1906         r = process_match(bus, m);
1907         if (r != 0)
1908                 return r;
1909
1910         r = process_builtin(bus, m);
1911         if (r != 0)
1912                 return r;
1913
1914         r = process_object(bus, m);
1915         if (r != 0)
1916                 return r;
1917
1918         return process_introspect(bus, m);
1919 }
1920
1921 static int process_running(sd_bus *bus, sd_bus_message **ret) {
1922         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
1923         int r;
1924
1925         assert(bus);
1926         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1927
1928         r = process_timeout(bus);
1929         if (r != 0)
1930                 goto null_message;
1931
1932         r = dispatch_wqueue(bus);
1933         if (r != 0)
1934                 goto null_message;
1935
1936         r = dispatch_rqueue(bus, &m);
1937         if (r < 0)
1938                 return r;
1939         if (!m)
1940                 goto null_message;
1941
1942         r = process_message(bus, m);
1943         if (r != 0)
1944                 goto null_message;
1945
1946         if (ret) {
1947                 r = sd_bus_message_rewind(m, true);
1948                 if (r < 0)
1949                         return r;
1950
1951                 *ret = m;
1952                 m = NULL;
1953                 return 1;
1954         }
1955
1956         if (m->header->type == SD_BUS_MESSAGE_TYPE_METHOD_CALL) {
1957                 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1958                 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1959
1960                 sd_bus_error_set(&error, "org.freedesktop.DBus.Error.UnknownObject", "Unknown object '%s'.", m->path);
1961
1962                 r = sd_bus_message_new_method_error(bus, m, &error, &reply);
1963                 if (r < 0)
1964                         return r;
1965
1966                 r = sd_bus_send(bus, reply, NULL);
1967                 if (r < 0)
1968                         return r;
1969         }
1970
1971         return 1;
1972
1973 null_message:
1974         if (r >= 0 && ret)
1975                 *ret = NULL;
1976
1977         return r;
1978 }
1979
1980 int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
1981         int r;
1982
1983         /* Returns 0 when we didn't do anything. This should cause the
1984          * caller to invoke sd_bus_wait() before returning the next
1985          * time. Returns > 0 when we did something, which possibly
1986          * means *ret is filled in with an unprocessed message. */
1987
1988         if (!bus)
1989                 return -EINVAL;
1990         if (bus->input_fd < 0)
1991                 return -ENOTCONN;
1992
1993         /* We don't allow recursively invoking sd_bus_process(). */
1994         if (bus->processing)
1995                 return -EBUSY;
1996
1997         switch (bus->state) {
1998
1999         case BUS_UNSET:
2000                 return -ENOTCONN;
2001
2002         case BUS_OPENING:
2003                 r = bus_socket_process_opening(bus);
2004                 if (r < 0)
2005                         return r;
2006                 if (ret)
2007                         *ret = NULL;
2008                 return r;
2009
2010         case BUS_AUTHENTICATING:
2011
2012                 r = bus_socket_process_authenticating(bus);
2013                 if (r < 0)
2014                         return r;
2015                 if (ret)
2016                         *ret = NULL;
2017                 return r;
2018
2019         case BUS_RUNNING:
2020         case BUS_HELLO:
2021
2022                 bus->processing = true;
2023                 r = process_running(bus, ret);
2024                 bus->processing = false;
2025
2026                 return r;
2027         }
2028
2029         assert_not_reached("Unknown state");
2030 }
2031
2032 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2033         struct pollfd p[2] = {};
2034         int r, e, n;
2035         struct timespec ts;
2036         usec_t until, m;
2037
2038         assert(bus);
2039
2040         if (bus->input_fd < 0)
2041                 return -ENOTCONN;
2042
2043         e = sd_bus_get_events(bus);
2044         if (e < 0)
2045                 return e;
2046
2047         if (need_more)
2048                 e |= POLLIN;
2049
2050         r = sd_bus_get_timeout(bus, &until);
2051         if (r < 0)
2052                 return r;
2053         if (r == 0)
2054                 m = (uint64_t) -1;
2055         else {
2056                 usec_t nw;
2057                 nw = now(CLOCK_MONOTONIC);
2058                 m = until > nw ? until - nw : 0;
2059         }
2060
2061         if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
2062                 m = timeout_usec;
2063
2064         p[0].fd = bus->input_fd;
2065         if (bus->output_fd == bus->input_fd) {
2066                 p[0].events = e;
2067                 n = 1;
2068         } else {
2069                 p[0].events = e & POLLIN;
2070                 p[1].fd = bus->output_fd;
2071                 p[1].events = e & POLLOUT;
2072                 n = 2;
2073         }
2074
2075         r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
2076         if (r < 0)
2077                 return -errno;
2078
2079         return r > 0 ? 1 : 0;
2080 }
2081
2082 int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
2083
2084         if (!bus)
2085                 return -EINVAL;
2086         if (bus->state == BUS_UNSET)
2087                 return -ENOTCONN;
2088         if (bus->input_fd < 0)
2089                 return -ENOTCONN;
2090         if (bus->rqueue_size > 0)
2091                 return 0;
2092
2093         return bus_poll(bus, false, timeout_usec);
2094 }
2095
2096 int sd_bus_flush(sd_bus *bus) {
2097         int r;
2098
2099         if (!bus)
2100                 return -EINVAL;
2101         if (bus->state == BUS_UNSET)
2102                 return -ENOTCONN;
2103         if (bus->output_fd < 0)
2104                 return -ENOTCONN;
2105
2106         r = bus_ensure_running(bus);
2107         if (r < 0)
2108                 return r;
2109
2110         if (bus->wqueue_size <= 0)
2111                 return 0;
2112
2113         for (;;) {
2114                 r = dispatch_wqueue(bus);
2115                 if (r < 0)
2116                         return r;
2117
2118                 if (bus->wqueue_size <= 0)
2119                         return 0;
2120
2121                 r = bus_poll(bus, false, (uint64_t) -1);
2122                 if (r < 0)
2123                         return r;
2124         }
2125 }
2126
2127 int sd_bus_add_filter(sd_bus *bus, sd_bus_message_handler_t callback, void *userdata) {
2128         struct filter_callback *f;
2129
2130         if (!bus)
2131                 return -EINVAL;
2132         if (!callback)
2133                 return -EINVAL;
2134
2135         f = new0(struct filter_callback, 1);
2136         if (!f)
2137                 return -ENOMEM;
2138         f->callback = callback;
2139         f->userdata = userdata;
2140
2141         bus->filter_callbacks_modified = true;
2142         LIST_PREPEND(struct filter_callback, callbacks, bus->filter_callbacks, f);
2143         return 0;
2144 }
2145
2146 int sd_bus_remove_filter(sd_bus *bus, sd_bus_message_handler_t callback, void *userdata) {
2147         struct filter_callback *f;
2148
2149         if (!bus)
2150                 return -EINVAL;
2151         if (!callback)
2152                 return -EINVAL;
2153
2154         LIST_FOREACH(callbacks, f, bus->filter_callbacks) {
2155                 if (f->callback == callback && f->userdata == userdata) {
2156                         bus->filter_callbacks_modified = true;
2157                         LIST_REMOVE(struct filter_callback, callbacks, bus->filter_callbacks, f);
2158                         free(f);
2159                         return 1;
2160                 }
2161         }
2162
2163         return 0;
2164 }
2165
2166 static int bus_add_object(
2167                 sd_bus *bus,
2168                 bool fallback,
2169                 const char *path,
2170                 sd_bus_message_handler_t callback,
2171                 void *userdata) {
2172
2173         struct object_callback *c;
2174         int r;
2175
2176         if (!bus)
2177                 return -EINVAL;
2178         if (!path)
2179                 return -EINVAL;
2180         if (!callback)
2181                 return -EINVAL;
2182
2183         r = hashmap_ensure_allocated(&bus->object_callbacks, string_hash_func, string_compare_func);
2184         if (r < 0)
2185                 return r;
2186
2187         c = new0(struct object_callback, 1);
2188         if (!c)
2189                 return -ENOMEM;
2190
2191         c->path = strdup(path);
2192         if (!c->path) {
2193                 free(c);
2194                 return -ENOMEM;
2195         }
2196
2197         c->callback = callback;
2198         c->userdata = userdata;
2199         c->is_fallback = fallback;
2200
2201         bus->object_callbacks_modified = true;
2202         r = hashmap_put(bus->object_callbacks, c->path, c);
2203         if (r < 0) {
2204                 free(c->path);
2205                 free(c);
2206                 return r;
2207         }
2208
2209         return 0;
2210 }
2211
2212 static int bus_remove_object(
2213                 sd_bus *bus,
2214                 bool fallback,
2215                 const char *path,
2216                 sd_bus_message_handler_t callback,
2217                 void *userdata) {
2218
2219         struct object_callback *c;
2220
2221         if (!bus)
2222                 return -EINVAL;
2223         if (!path)
2224                 return -EINVAL;
2225         if (!callback)
2226                 return -EINVAL;
2227
2228         c = hashmap_get(bus->object_callbacks, path);
2229         if (!c)
2230                 return 0;
2231
2232         if (c->callback != callback || c->userdata != userdata || c->is_fallback != fallback)
2233                 return 0;
2234
2235         bus->object_callbacks_modified = true;
2236         assert_se(c == hashmap_remove(bus->object_callbacks, c->path));
2237
2238         free(c->path);
2239         free(c);
2240
2241         return 1;
2242 }
2243
2244 int sd_bus_add_object(sd_bus *bus, const char *path, sd_bus_message_handler_t callback, void *userdata) {
2245         return bus_add_object(bus, false, path, callback, userdata);
2246 }
2247
2248 int sd_bus_remove_object(sd_bus *bus, const char *path, sd_bus_message_handler_t callback, void *userdata) {
2249         return bus_remove_object(bus, false, path, callback, userdata);
2250 }
2251
2252 int sd_bus_add_fallback(sd_bus *bus, const char *prefix, sd_bus_message_handler_t callback, void *userdata) {
2253         return bus_add_object(bus, true, prefix, callback, userdata);
2254 }
2255
2256 int sd_bus_remove_fallback(sd_bus *bus, const char *prefix, sd_bus_message_handler_t callback, void *userdata) {
2257         return bus_remove_object(bus, true, prefix, callback, userdata);
2258 }
2259
2260 int sd_bus_add_match(sd_bus *bus, const char *match, sd_bus_message_handler_t callback, void *userdata) {
2261         int r = 0;
2262
2263         if (!bus)
2264                 return -EINVAL;
2265         if (!match)
2266                 return -EINVAL;
2267
2268         if (bus->bus_client) {
2269                 r = bus_add_match_internal(bus, match);
2270                 if (r < 0)
2271                         return r;
2272         }
2273
2274         if (callback) {
2275                 bus->match_callbacks_modified = true;
2276                 r = bus_match_add(&bus->match_callbacks, match, callback, userdata, NULL);
2277                 if (r < 0) {
2278
2279                         if (bus->bus_client)
2280                                 bus_remove_match_internal(bus, match);
2281                 }
2282         }
2283
2284         return r;
2285 }
2286
2287 int sd_bus_remove_match(sd_bus *bus, const char *match, sd_bus_message_handler_t callback, void *userdata) {
2288         int r = 0, q = 0;
2289
2290         if (!bus)
2291                 return -EINVAL;
2292         if (!match)
2293                 return -EINVAL;
2294
2295         if (bus->bus_client)
2296                 r = bus_remove_match_internal(bus, match);
2297
2298         if (callback) {
2299                 bus->match_callbacks_modified = true;
2300                 q = bus_match_remove(&bus->match_callbacks, match, callback, userdata);
2301         }
2302
2303         if (r < 0)
2304                 return r;
2305         return q;
2306 }
2307
2308 int sd_bus_emit_signal(
2309                 sd_bus *bus,
2310                 const char *path,
2311                 const char *interface,
2312                 const char *member,
2313                 const char *types, ...) {
2314
2315         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2316         va_list ap;
2317         int r;
2318
2319         if (!bus)
2320                 return -EINVAL;
2321
2322         r = sd_bus_message_new_signal(bus, path, interface, member, &m);
2323         if (r < 0)
2324                 return r;
2325
2326         va_start(ap, types);
2327         r = bus_message_append_ap(m, types, ap);
2328         va_end(ap);
2329         if (r < 0)
2330                 return r;
2331
2332         return sd_bus_send(bus, m, NULL);
2333 }
2334
2335 int sd_bus_call_method(
2336                 sd_bus *bus,
2337                 const char *destination,
2338                 const char *path,
2339                 const char *interface,
2340                 const char *member,
2341                 sd_bus_error *error,
2342                 sd_bus_message **reply,
2343                 const char *types, ...) {
2344
2345         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2346         va_list ap;
2347         int r;
2348
2349         if (!bus)
2350                 return -EINVAL;
2351
2352         r = sd_bus_message_new_method_call(bus, destination, path, interface, member, &m);
2353         if (r < 0)
2354                 return r;
2355
2356         va_start(ap, types);
2357         r = bus_message_append_ap(m, types, ap);
2358         va_end(ap);
2359         if (r < 0)
2360                 return r;
2361
2362         return sd_bus_send_with_reply_and_block(bus, m, 0, error, reply);
2363 }
2364
2365 int sd_bus_reply_method_return(
2366                 sd_bus *bus,
2367                 sd_bus_message *call,
2368                 const char *types, ...) {
2369
2370         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2371         va_list ap;
2372         int r;
2373
2374         if (!bus)
2375                 return -EINVAL;
2376         if (!call)
2377                 return -EINVAL;
2378         if (!call->sealed)
2379                 return -EPERM;
2380         if (call->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
2381                 return -EINVAL;
2382
2383         if (call->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED)
2384                 return 0;
2385
2386         r = sd_bus_message_new_method_return(bus, call, &m);
2387         if (r < 0)
2388                 return r;
2389
2390         va_start(ap, types);
2391         r = bus_message_append_ap(m, types, ap);
2392         va_end(ap);
2393         if (r < 0)
2394                 return r;
2395
2396         return sd_bus_send(bus, m, NULL);
2397 }
2398
2399 int sd_bus_reply_method_error(
2400                 sd_bus *bus,
2401                 sd_bus_message *call,
2402                 const sd_bus_error *e) {
2403
2404         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2405         int r;
2406
2407         if (!bus)
2408                 return -EINVAL;
2409         if (!call)
2410                 return -EINVAL;
2411         if (!call->sealed)
2412                 return -EPERM;
2413         if (call->header->type != SD_BUS_MESSAGE_TYPE_METHOD_CALL)
2414                 return -EINVAL;
2415         if (!sd_bus_error_is_set(e))
2416                 return -EINVAL;
2417
2418         if (call->header->flags & SD_BUS_MESSAGE_NO_REPLY_EXPECTED)
2419                 return 0;
2420
2421         r = sd_bus_message_new_method_error(bus, call, e, &m);
2422         if (r < 0)
2423                 return r;
2424
2425         return sd_bus_send(bus, m, NULL);
2426 }