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