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