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