chiark / gitweb /
event: make gcc shut up
[elogind.git] / src / libsystemd-bus / sd-bus.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2013 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <endian.h>
23 #include <assert.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <netdb.h>
27 #include <sys/poll.h>
28 #include <byteswap.h>
29 #include <sys/mman.h>
30 #include <pthread.h>
31
32 #include "util.h"
33 #include "macro.h"
34 #include "strv.h"
35 #include "set.h"
36 #include "missing.h"
37
38 #include "sd-bus.h"
39 #include "bus-internal.h"
40 #include "bus-message.h"
41 #include "bus-type.h"
42 #include "bus-socket.h"
43 #include "bus-kernel.h"
44 #include "bus-control.h"
45 #include "bus-introspect.h"
46 #include "bus-signature.h"
47 #include "bus-objects.h"
48 #include "bus-util.h"
49 #include "bus-container.h"
50 #include "bus-protocol.h"
51
52 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec);
53 static int attach_io_events(sd_bus *b);
54 static void detach_io_events(sd_bus *b);
55
56 static void bus_close_fds(sd_bus *b) {
57         assert(b);
58
59         detach_io_events(b);
60
61         if (b->input_fd >= 0)
62                 close_nointr_nofail(b->input_fd);
63
64         if (b->output_fd >= 0 && b->output_fd != b->input_fd)
65                 close_nointr_nofail(b->output_fd);
66
67         b->input_fd = b->output_fd = -1;
68 }
69
70 static void bus_node_destroy(sd_bus *b, struct node *n) {
71         struct node_callback *c;
72         struct node_vtable *v;
73         struct node_enumerator *e;
74
75         assert(b);
76
77         if (!n)
78                 return;
79
80         while (n->child)
81                 bus_node_destroy(b, n->child);
82
83         while ((c = n->callbacks)) {
84                 LIST_REMOVE(callbacks, n->callbacks, c);
85                 free(c);
86         }
87
88         while ((v = n->vtables)) {
89                 LIST_REMOVE(vtables, n->vtables, v);
90                 free(v->interface);
91                 free(v);
92         }
93
94         while ((e = n->enumerators)) {
95                 LIST_REMOVE(enumerators, n->enumerators, e);
96                 free(e);
97         }
98
99         if (n->parent)
100                 LIST_REMOVE(siblings, n->parent->child, n);
101
102         assert_se(hashmap_remove(b->nodes, n->path) == n);
103         free(n->path);
104         free(n);
105 }
106
107 static void bus_reset_queues(sd_bus *b) {
108         unsigned i;
109
110         assert(b);
111
112         for (i = 0; i < b->rqueue_size; i++)
113                 sd_bus_message_unref(b->rqueue[i]);
114         free(b->rqueue);
115
116         for (i = 0; i < b->wqueue_size; i++)
117                 sd_bus_message_unref(b->wqueue[i]);
118         free(b->wqueue);
119
120         b->rqueue = b->wqueue = NULL;
121         b->rqueue_size = b->wqueue_size = 0;
122 }
123
124 static void bus_free(sd_bus *b) {
125         struct filter_callback *f;
126         struct node *n;
127
128         assert(b);
129
130         sd_bus_detach_event(b);
131
132         bus_close_fds(b);
133
134         if (b->kdbus_buffer)
135                 munmap(b->kdbus_buffer, KDBUS_POOL_SIZE);
136
137         free(b->rbuffer);
138         free(b->unique_name);
139         free(b->auth_buffer);
140         free(b->address);
141         free(b->kernel);
142         free(b->machine);
143
144         free(b->exec_path);
145         strv_free(b->exec_argv);
146
147         close_many(b->fds, b->n_fds);
148         free(b->fds);
149
150         bus_reset_queues(b);
151
152         hashmap_free_free(b->reply_callbacks);
153         prioq_free(b->reply_callbacks_prioq);
154
155         while ((f = b->filter_callbacks)) {
156                 LIST_REMOVE(callbacks, b->filter_callbacks, f);
157                 free(f);
158         }
159
160         bus_match_free(&b->match_callbacks);
161
162         hashmap_free_free(b->vtable_methods);
163         hashmap_free_free(b->vtable_properties);
164
165         while ((n = hashmap_first(b->nodes)))
166                 bus_node_destroy(b, n);
167
168         hashmap_free(b->nodes);
169
170         bus_kernel_flush_memfd(b);
171
172         assert_se(pthread_mutex_destroy(&b->memfd_cache_mutex) == 0);
173
174         free(b);
175 }
176
177 _public_ int sd_bus_new(sd_bus **ret) {
178         sd_bus *r;
179
180         assert_return(ret, -EINVAL);
181
182         r = new0(sd_bus, 1);
183         if (!r)
184                 return -ENOMEM;
185
186         r->n_ref = REFCNT_INIT;
187         r->input_fd = r->output_fd = -1;
188         r->message_version = 1;
189         r->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
190         r->hello_flags |= KDBUS_HELLO_ACCEPT_FD;
191         r->attach_flags |= KDBUS_ATTACH_NAMES;
192         r->original_pid = getpid();
193
194         assert_se(pthread_mutex_init(&r->memfd_cache_mutex, NULL) == 0);
195
196         /* We guarantee that wqueue always has space for at least one
197          * entry */
198         r->wqueue = new(sd_bus_message*, 1);
199         if (!r->wqueue) {
200                 free(r);
201                 return -ENOMEM;
202         }
203
204         *ret = r;
205         return 0;
206 }
207
208 _public_ int sd_bus_set_address(sd_bus *bus, const char *address) {
209         char *a;
210
211         assert_return(bus, -EINVAL);
212         assert_return(bus->state == BUS_UNSET, -EPERM);
213         assert_return(address, -EINVAL);
214         assert_return(!bus_pid_changed(bus), -ECHILD);
215
216         a = strdup(address);
217         if (!a)
218                 return -ENOMEM;
219
220         free(bus->address);
221         bus->address = a;
222
223         return 0;
224 }
225
226 _public_ int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd) {
227         assert_return(bus, -EINVAL);
228         assert_return(bus->state == BUS_UNSET, -EPERM);
229         assert_return(input_fd >= 0, -EINVAL);
230         assert_return(output_fd >= 0, -EINVAL);
231         assert_return(!bus_pid_changed(bus), -ECHILD);
232
233         bus->input_fd = input_fd;
234         bus->output_fd = output_fd;
235         return 0;
236 }
237
238 _public_ int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]) {
239         char *p, **a;
240
241         assert_return(bus, -EINVAL);
242         assert_return(bus->state == BUS_UNSET, -EPERM);
243         assert_return(path, -EINVAL);
244         assert_return(!strv_isempty(argv), -EINVAL);
245         assert_return(!bus_pid_changed(bus), -ECHILD);
246
247         p = strdup(path);
248         if (!p)
249                 return -ENOMEM;
250
251         a = strv_copy(argv);
252         if (!a) {
253                 free(p);
254                 return -ENOMEM;
255         }
256
257         free(bus->exec_path);
258         strv_free(bus->exec_argv);
259
260         bus->exec_path = p;
261         bus->exec_argv = a;
262
263         return 0;
264 }
265
266 _public_ int sd_bus_set_bus_client(sd_bus *bus, int b) {
267         assert_return(bus, -EINVAL);
268         assert_return(bus->state == BUS_UNSET, -EPERM);
269         assert_return(!bus_pid_changed(bus), -ECHILD);
270
271         bus->bus_client = !!b;
272         return 0;
273 }
274
275 _public_ int sd_bus_negotiate_fds(sd_bus *bus, int b) {
276         assert_return(bus, -EINVAL);
277         assert_return(bus->state == BUS_UNSET, -EPERM);
278         assert_return(!bus_pid_changed(bus), -ECHILD);
279
280         SET_FLAG(bus->hello_flags, KDBUS_HELLO_ACCEPT_FD, b);
281         return 0;
282 }
283
284 _public_ int sd_bus_negotiate_attach_timestamp(sd_bus *bus, int b) {
285         assert_return(bus, -EINVAL);
286         assert_return(bus->state == BUS_UNSET, -EPERM);
287         assert_return(!bus_pid_changed(bus), -ECHILD);
288
289         SET_FLAG(bus->attach_flags, KDBUS_ATTACH_TIMESTAMP, b);
290         return 0;
291 }
292
293 _public_ int sd_bus_negotiate_attach_creds(sd_bus *bus, uint64_t mask) {
294         assert_return(bus, -EINVAL);
295         assert_return(mask <= _SD_BUS_CREDS_ALL, -EINVAL);
296         assert_return(bus->state == BUS_UNSET, -EPERM);
297         assert_return(!bus_pid_changed(bus), -ECHILD);
298
299         /* The well knowns we need unconditionally, so that matches can work */
300         bus->creds_mask = mask | SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
301
302         return kdbus_translate_attach_flags(bus->creds_mask, &bus->creds_mask);
303 }
304
305 _public_ int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id) {
306         assert_return(bus, -EINVAL);
307         assert_return(b || sd_id128_equal(server_id, SD_ID128_NULL), -EINVAL);
308         assert_return(bus->state == BUS_UNSET, -EPERM);
309         assert_return(!bus_pid_changed(bus), -ECHILD);
310
311         bus->is_server = !!b;
312         bus->server_id = server_id;
313         return 0;
314 }
315
316 _public_ int sd_bus_set_anonymous(sd_bus *bus, int b) {
317         assert_return(bus, -EINVAL);
318         assert_return(bus->state == BUS_UNSET, -EPERM);
319         assert_return(!bus_pid_changed(bus), -ECHILD);
320
321         bus->anonymous_auth = !!b;
322         return 0;
323 }
324
325 _public_ int sd_bus_set_trusted(sd_bus *bus, int b) {
326         assert_return(bus, -EINVAL);
327         assert_return(bus->state == BUS_UNSET, -EPERM);
328         assert_return(!bus_pid_changed(bus), -ECHILD);
329
330         bus->trusted = !!b;
331         return 0;
332 }
333
334 static int hello_callback(sd_bus *bus, sd_bus_message *reply, void *userdata, sd_bus_error *error) {
335         const char *s;
336         int r;
337
338         assert(bus);
339         assert(bus->state == BUS_HELLO || bus->state == BUS_CLOSING);
340         assert(reply);
341
342         r = sd_bus_message_get_errno(reply);
343         if (r < 0)
344                 return r;
345         if (r > 0)
346                 return -r;
347
348         r = sd_bus_message_read(reply, "s", &s);
349         if (r < 0)
350                 return r;
351
352         if (!service_name_is_valid(s) || s[0] != ':')
353                 return -EBADMSG;
354
355         bus->unique_name = strdup(s);
356         if (!bus->unique_name)
357                 return -ENOMEM;
358
359         if (bus->state == BUS_HELLO)
360                 bus->state = BUS_RUNNING;
361
362         return 1;
363 }
364
365 static int bus_send_hello(sd_bus *bus) {
366         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
367         int r;
368
369         assert(bus);
370
371         if (!bus->bus_client || bus->is_kernel)
372                 return 0;
373
374         r = sd_bus_message_new_method_call(
375                         bus,
376                         "org.freedesktop.DBus",
377                         "/",
378                         "org.freedesktop.DBus",
379                         "Hello",
380                         &m);
381         if (r < 0)
382                 return r;
383
384         return sd_bus_call_async(bus, m, hello_callback, NULL, 0, &bus->hello_serial);
385 }
386
387 int bus_start_running(sd_bus *bus) {
388         assert(bus);
389
390         if (bus->bus_client && !bus->is_kernel) {
391                 bus->state = BUS_HELLO;
392                 return 1;
393         }
394
395         bus->state = BUS_RUNNING;
396         return 1;
397 }
398
399 static int parse_address_key(const char **p, const char *key, char **value) {
400         size_t l, n = 0;
401         const char *a;
402         char *r = NULL;
403
404         assert(p);
405         assert(*p);
406         assert(value);
407
408         if (key) {
409                 l = strlen(key);
410                 if (strncmp(*p, key, l) != 0)
411                         return 0;
412
413                 if ((*p)[l] != '=')
414                         return 0;
415
416                 if (*value)
417                         return -EINVAL;
418
419                 a = *p + l + 1;
420         } else
421                 a = *p;
422
423         while (*a != ';' && *a != ',' && *a != 0) {
424                 char c, *t;
425
426                 if (*a == '%') {
427                         int x, y;
428
429                         x = unhexchar(a[1]);
430                         if (x < 0) {
431                                 free(r);
432                                 return x;
433                         }
434
435                         y = unhexchar(a[2]);
436                         if (y < 0) {
437                                 free(r);
438                                 return y;
439                         }
440
441                         c = (char) ((x << 4) | y);
442                         a += 3;
443                 } else {
444                         c = *a;
445                         a++;
446                 }
447
448                 t = realloc(r, n + 2);
449                 if (!t) {
450                         free(r);
451                         return -ENOMEM;
452                 }
453
454                 r = t;
455                 r[n++] = c;
456         }
457
458         if (!r) {
459                 r = strdup("");
460                 if (!r)
461                         return -ENOMEM;
462         } else
463                 r[n] = 0;
464
465         if (*a == ',')
466                 a++;
467
468         *p = a;
469
470         free(*value);
471         *value = r;
472
473         return 1;
474 }
475
476 static void skip_address_key(const char **p) {
477         assert(p);
478         assert(*p);
479
480         *p += strcspn(*p, ",");
481
482         if (**p == ',')
483                 (*p) ++;
484 }
485
486 static int parse_unix_address(sd_bus *b, const char **p, char **guid) {
487         _cleanup_free_ char *path = NULL, *abstract = NULL;
488         size_t l;
489         int r;
490
491         assert(b);
492         assert(p);
493         assert(*p);
494         assert(guid);
495
496         while (**p != 0 && **p != ';') {
497                 r = parse_address_key(p, "guid", guid);
498                 if (r < 0)
499                         return r;
500                 else if (r > 0)
501                         continue;
502
503                 r = parse_address_key(p, "path", &path);
504                 if (r < 0)
505                         return r;
506                 else if (r > 0)
507                         continue;
508
509                 r = parse_address_key(p, "abstract", &abstract);
510                 if (r < 0)
511                         return r;
512                 else if (r > 0)
513                         continue;
514
515                 skip_address_key(p);
516         }
517
518         if (!path && !abstract)
519                 return -EINVAL;
520
521         if (path && abstract)
522                 return -EINVAL;
523
524         if (path) {
525                 l = strlen(path);
526                 if (l > sizeof(b->sockaddr.un.sun_path))
527                         return -E2BIG;
528
529                 b->sockaddr.un.sun_family = AF_UNIX;
530                 strncpy(b->sockaddr.un.sun_path, path, sizeof(b->sockaddr.un.sun_path));
531                 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l;
532         } else if (abstract) {
533                 l = strlen(abstract);
534                 if (l > sizeof(b->sockaddr.un.sun_path) - 1)
535                         return -E2BIG;
536
537                 b->sockaddr.un.sun_family = AF_UNIX;
538                 b->sockaddr.un.sun_path[0] = 0;
539                 strncpy(b->sockaddr.un.sun_path+1, abstract, sizeof(b->sockaddr.un.sun_path)-1);
540                 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
541         }
542
543         return 0;
544 }
545
546 static int parse_tcp_address(sd_bus *b, const char **p, char **guid) {
547         _cleanup_free_ char *host = NULL, *port = NULL, *family = NULL;
548         int r;
549         struct addrinfo *result, hints = {
550                 .ai_socktype = SOCK_STREAM,
551                 .ai_flags = AI_ADDRCONFIG,
552         };
553
554         assert(b);
555         assert(p);
556         assert(*p);
557         assert(guid);
558
559         while (**p != 0 && **p != ';') {
560                 r = parse_address_key(p, "guid", guid);
561                 if (r < 0)
562                         return r;
563                 else if (r > 0)
564                         continue;
565
566                 r = parse_address_key(p, "host", &host);
567                 if (r < 0)
568                         return r;
569                 else if (r > 0)
570                         continue;
571
572                 r = parse_address_key(p, "port", &port);
573                 if (r < 0)
574                         return r;
575                 else if (r > 0)
576                         continue;
577
578                 r = parse_address_key(p, "family", &family);
579                 if (r < 0)
580                         return r;
581                 else if (r > 0)
582                         continue;
583
584                 skip_address_key(p);
585         }
586
587         if (!host || !port)
588                 return -EINVAL;
589
590         if (family) {
591                 if (streq(family, "ipv4"))
592                         hints.ai_family = AF_INET;
593                 else if (streq(family, "ipv6"))
594                         hints.ai_family = AF_INET6;
595                 else
596                         return -EINVAL;
597         }
598
599         r = getaddrinfo(host, port, &hints, &result);
600         if (r == EAI_SYSTEM)
601                 return -errno;
602         else if (r != 0)
603                 return -EADDRNOTAVAIL;
604
605         memcpy(&b->sockaddr, result->ai_addr, result->ai_addrlen);
606         b->sockaddr_size = result->ai_addrlen;
607
608         freeaddrinfo(result);
609
610         return 0;
611 }
612
613 static int parse_exec_address(sd_bus *b, const char **p, char **guid) {
614         char *path = NULL;
615         unsigned n_argv = 0, j;
616         char **argv = 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                         goto fail;
628                 else if (r > 0)
629                         continue;
630
631                 r = parse_address_key(p, "path", &path);
632                 if (r < 0)
633                         goto fail;
634                 else if (r > 0)
635                         continue;
636
637                 if (startswith(*p, "argv")) {
638                         unsigned ul;
639
640                         errno = 0;
641                         ul = strtoul(*p + 4, (char**) p, 10);
642                         if (errno > 0 || **p != '=' || ul > 256) {
643                                 r = -EINVAL;
644                                 goto fail;
645                         }
646
647                         (*p) ++;
648
649                         if (ul >= n_argv) {
650                                 char **x;
651
652                                 x = realloc(argv, sizeof(char*) * (ul + 2));
653                                 if (!x) {
654                                         r = -ENOMEM;
655                                         goto fail;
656                                 }
657
658                                 memset(x + n_argv, 0, sizeof(char*) * (ul - n_argv + 2));
659
660                                 argv = x;
661                                 n_argv = ul + 1;
662                         }
663
664                         r = parse_address_key(p, NULL, argv + ul);
665                         if (r < 0)
666                                 goto fail;
667
668                         continue;
669                 }
670
671                 skip_address_key(p);
672         }
673
674         if (!path) {
675                 r = -EINVAL;
676                 goto fail;
677         }
678
679         /* Make sure there are no holes in the array, with the
680          * exception of argv[0] */
681         for (j = 1; j < n_argv; j++)
682                 if (!argv[j]) {
683                         r = -EINVAL;
684                         goto fail;
685                 }
686
687         if (argv && argv[0] == NULL) {
688                 argv[0] = strdup(path);
689                 if (!argv[0]) {
690                         r = -ENOMEM;
691                         goto fail;
692                 }
693         }
694
695         b->exec_path = path;
696         b->exec_argv = argv;
697         return 0;
698
699 fail:
700         for (j = 0; j < n_argv; j++)
701                 free(argv[j]);
702
703         free(argv);
704         free(path);
705         return r;
706 }
707
708 static int parse_kernel_address(sd_bus *b, const char **p, char **guid) {
709         _cleanup_free_ char *path = NULL;
710         int r;
711
712         assert(b);
713         assert(p);
714         assert(*p);
715         assert(guid);
716
717         while (**p != 0 && **p != ';') {
718                 r = parse_address_key(p, "guid", guid);
719                 if (r < 0)
720                         return r;
721                 else if (r > 0)
722                         continue;
723
724                 r = parse_address_key(p, "path", &path);
725                 if (r < 0)
726                         return r;
727                 else if (r > 0)
728                         continue;
729
730                 skip_address_key(p);
731         }
732
733         if (!path)
734                 return -EINVAL;
735
736         free(b->kernel);
737         b->kernel = path;
738         path = NULL;
739
740         return 0;
741 }
742
743 static int parse_container_address(sd_bus *b, const char **p, char **guid) {
744         _cleanup_free_ char *machine = NULL;
745         int r;
746
747         assert(b);
748         assert(p);
749         assert(*p);
750         assert(guid);
751
752         while (**p != 0 && **p != ';') {
753                 r = parse_address_key(p, "guid", guid);
754                 if (r < 0)
755                         return r;
756                 else if (r > 0)
757                         continue;
758
759                 r = parse_address_key(p, "machine", &machine);
760                 if (r < 0)
761                         return r;
762                 else if (r > 0)
763                         continue;
764
765                 skip_address_key(p);
766         }
767
768         if (!machine)
769                 return -EINVAL;
770
771         if (!filename_is_safe(machine))
772                 return -EINVAL;
773
774         free(b->machine);
775         b->machine = machine;
776         machine = NULL;
777
778         b->sockaddr.un.sun_family = AF_UNIX;
779         strncpy(b->sockaddr.un.sun_path, "/var/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
780         b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + sizeof("/var/run/dbus/system_bus_socket") - 1;
781
782         return 0;
783 }
784
785 static void bus_reset_parsed_address(sd_bus *b) {
786         assert(b);
787
788         zero(b->sockaddr);
789         b->sockaddr_size = 0;
790         strv_free(b->exec_argv);
791         free(b->exec_path);
792         b->exec_path = NULL;
793         b->exec_argv = NULL;
794         b->server_id = SD_ID128_NULL;
795         free(b->kernel);
796         b->kernel = NULL;
797         free(b->machine);
798         b->machine = NULL;
799 }
800
801 static int bus_parse_next_address(sd_bus *b) {
802         _cleanup_free_ char *guid = NULL;
803         const char *a;
804         int r;
805
806         assert(b);
807
808         if (!b->address)
809                 return 0;
810         if (b->address[b->address_index] == 0)
811                 return 0;
812
813         bus_reset_parsed_address(b);
814
815         a = b->address + b->address_index;
816
817         while (*a != 0) {
818
819                 if (*a == ';') {
820                         a++;
821                         continue;
822                 }
823
824                 if (startswith(a, "unix:")) {
825                         a += 5;
826
827                         r = parse_unix_address(b, &a, &guid);
828                         if (r < 0)
829                                 return r;
830                         break;
831
832                 } else if (startswith(a, "tcp:")) {
833
834                         a += 4;
835                         r = parse_tcp_address(b, &a, &guid);
836                         if (r < 0)
837                                 return r;
838
839                         break;
840
841                 } else if (startswith(a, "unixexec:")) {
842
843                         a += 9;
844                         r = parse_exec_address(b, &a, &guid);
845                         if (r < 0)
846                                 return r;
847
848                         break;
849
850                 } else if (startswith(a, "kernel:")) {
851
852                         a += 7;
853                         r = parse_kernel_address(b, &a, &guid);
854                         if (r < 0)
855                                 return r;
856
857                         break;
858                 } else if (startswith(a, "x-container:")) {
859
860                         a += 12;
861                         r = parse_container_address(b, &a, &guid);
862                         if (r < 0)
863                                 return r;
864
865                         break;
866                 }
867
868                 a = strchr(a, ';');
869                 if (!a)
870                         return 0;
871         }
872
873         if (guid) {
874                 r = sd_id128_from_string(guid, &b->server_id);
875                 if (r < 0)
876                         return r;
877         }
878
879         b->address_index = a - b->address;
880         return 1;
881 }
882
883 static int bus_start_address(sd_bus *b) {
884         int r;
885
886         assert(b);
887
888         for (;;) {
889                 bool skipped = false;
890
891                 bus_close_fds(b);
892
893                 if (b->exec_path)
894                         r = bus_socket_exec(b);
895                 else if (b->kernel)
896                         r = bus_kernel_connect(b);
897                 else if (b->machine)
898                         r = bus_container_connect(b);
899                 else if (b->sockaddr.sa.sa_family != AF_UNSPEC)
900                         r = bus_socket_connect(b);
901                 else
902                         skipped = true;
903
904                 if (!skipped) {
905                         if (r >= 0) {
906                                 r = attach_io_events(b);
907                                 if (r >= 0)
908                                         return r;
909                         }
910
911                         b->last_connect_error = -r;
912                 }
913
914                 r = bus_parse_next_address(b);
915                 if (r < 0)
916                         return r;
917                 if (r == 0)
918                         return b->last_connect_error ? -b->last_connect_error : -ECONNREFUSED;
919         }
920 }
921
922 int bus_next_address(sd_bus *b) {
923         assert(b);
924
925         bus_reset_parsed_address(b);
926         return bus_start_address(b);
927 }
928
929 static int bus_start_fd(sd_bus *b) {
930         struct stat st;
931         int r;
932
933         assert(b);
934         assert(b->input_fd >= 0);
935         assert(b->output_fd >= 0);
936
937         r = fd_nonblock(b->input_fd, true);
938         if (r < 0)
939                 return r;
940
941         r = fd_cloexec(b->input_fd, true);
942         if (r < 0)
943                 return r;
944
945         if (b->input_fd != b->output_fd) {
946                 r = fd_nonblock(b->output_fd, true);
947                 if (r < 0)
948                         return r;
949
950                 r = fd_cloexec(b->output_fd, true);
951                 if (r < 0)
952                         return r;
953         }
954
955         if (fstat(b->input_fd, &st) < 0)
956                 return -errno;
957
958         if (S_ISCHR(b->input_fd))
959                 return bus_kernel_take_fd(b);
960         else
961                 return bus_socket_take_fd(b);
962 }
963
964 _public_ int sd_bus_start(sd_bus *bus) {
965         int r;
966
967         assert_return(bus, -EINVAL);
968         assert_return(bus->state == BUS_UNSET, -EPERM);
969         assert_return(!bus_pid_changed(bus), -ECHILD);
970
971         bus->state = BUS_OPENING;
972
973         if (bus->is_server && bus->bus_client)
974                 return -EINVAL;
975
976         if (bus->input_fd >= 0)
977                 r = bus_start_fd(bus);
978         else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->kernel || bus->machine)
979                 r = bus_start_address(bus);
980         else
981                 return -EINVAL;
982
983         if (r < 0)
984                 return r;
985
986         return bus_send_hello(bus);
987 }
988
989 _public_ int sd_bus_open_system(sd_bus **ret) {
990         const char *e;
991         sd_bus *b;
992         int r;
993
994         assert_return(ret, -EINVAL);
995
996         r = sd_bus_new(&b);
997         if (r < 0)
998                 return r;
999
1000         e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1001         if (e)
1002                 r = sd_bus_set_address(b, e);
1003         else
1004 #ifdef ENABLE_KDBUS
1005                 r = sd_bus_set_address(b, "kernel:path=/dev/kdbus/0-system/bus;unix:path=/run/dbus/system_bus_socket");
1006 #else
1007                 r = sd_bus_set_address(b, "unix:path=/run/dbus/system_bus_socket");
1008 #endif
1009
1010         if (r < 0)
1011                 goto fail;
1012
1013         b->bus_client = true;
1014
1015         /* Let's do per-method access control on the system bus. We
1016          * need the caller's UID and capability set for that. */
1017         b->trusted = false;
1018         b->attach_flags |= KDBUS_ATTACH_CAPS | KDBUS_ATTACH_CREDS;
1019
1020         r = sd_bus_start(b);
1021         if (r < 0)
1022                 goto fail;
1023
1024         *ret = b;
1025         return 0;
1026
1027 fail:
1028         bus_free(b);
1029         return r;
1030 }
1031
1032 _public_ int sd_bus_open_user(sd_bus **ret) {
1033         const char *e;
1034         sd_bus *b;
1035         int r;
1036
1037         assert_return(ret, -EINVAL);
1038
1039         r = sd_bus_new(&b);
1040         if (r < 0)
1041                 return r;
1042
1043         e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
1044         if (e) {
1045                 r = sd_bus_set_address(b, e);
1046                 if (r < 0)
1047                         goto fail;
1048         } else {
1049                 e = secure_getenv("XDG_RUNTIME_DIR");
1050                 if (e) {
1051                         _cleanup_free_ char *ee = NULL;
1052
1053                         ee = bus_address_escape(e);
1054                         if (!ee) {
1055                                 r = -ENOMEM;
1056                                 goto fail;
1057                         }
1058
1059 #ifdef ENABLE_KDBUS
1060                         asprintf(&b->address, "kernel:path=/dev/kdbus/%lu-user/bus;unix:path=%s/bus", (unsigned long) getuid(), ee);
1061 #else
1062                         b->address = strjoin("unix:path=", ee, "/bus", NULL);
1063 #endif
1064                 } else {
1065 #ifdef ENABLE_KDBUS
1066                         asprintf(&b->address, "kernel:path=/dev/kdbus/%lu-user/bus", (unsigned long) getuid());
1067 #else
1068                         return -ECONNREFUSED;
1069 #endif
1070                 }
1071
1072                 if (!b->address) {
1073                         r = -ENOMEM;
1074                         goto fail;
1075                 }
1076         }
1077
1078         b->bus_client = true;
1079
1080         /* We don't do any per-method access control on the user
1081          * bus. */
1082         b->trusted = true;
1083
1084         r = sd_bus_start(b);
1085         if (r < 0)
1086                 goto fail;
1087
1088         *ret = b;
1089         return 0;
1090
1091 fail:
1092         bus_free(b);
1093         return r;
1094 }
1095
1096 _public_ int sd_bus_open_system_remote(const char *host, sd_bus **ret) {
1097         _cleanup_free_ char *e = NULL;
1098         char *p = NULL;
1099         sd_bus *bus;
1100         int r;
1101
1102         assert_return(host, -EINVAL);
1103         assert_return(ret, -EINVAL);
1104
1105         e = bus_address_escape(host);
1106         if (!e)
1107                 return -ENOMEM;
1108
1109         p = strjoin("unixexec:path=ssh,argv1=-xT,argv2=", e, ",argv3=systemd-stdio-bridge", NULL);
1110         if (!p)
1111                 return -ENOMEM;
1112
1113         r = sd_bus_new(&bus);
1114         if (r < 0) {
1115                 free(p);
1116                 return r;
1117         }
1118
1119         bus->address = p;
1120         bus->bus_client = true;
1121
1122         r = sd_bus_start(bus);
1123         if (r < 0) {
1124                 bus_free(bus);
1125                 return r;
1126         }
1127
1128         *ret = bus;
1129         return 0;
1130 }
1131
1132 _public_ int sd_bus_open_system_container(const char *machine, sd_bus **ret) {
1133         _cleanup_free_ char *e = NULL;
1134         sd_bus *bus;
1135         char *p;
1136         int r;
1137
1138         assert_return(machine, -EINVAL);
1139         assert_return(ret, -EINVAL);
1140         assert_return(filename_is_safe(machine), -EINVAL);
1141
1142         e = bus_address_escape(machine);
1143         if (!e)
1144                 return -ENOMEM;
1145
1146 #ifdef ENABLE_KDBUS
1147         p = strjoin("kernel:path=/dev/kdbus/ns/machine-", e, "/0-system/bus;x-container:machine=", e, NULL);
1148 #else
1149         p = strjoin("x-container:machine=", e, NULL);
1150 #endif
1151         if (!p)
1152                 return -ENOMEM;
1153
1154         r = sd_bus_new(&bus);
1155         if (r < 0) {
1156                 free(p);
1157                 return r;
1158         }
1159
1160         bus->address = p;
1161         bus->bus_client = true;
1162
1163         r = sd_bus_start(bus);
1164         if (r < 0) {
1165                 bus_free(bus);
1166                 return r;
1167         }
1168
1169         *ret = bus;
1170         return 0;
1171 }
1172
1173 _public_ void sd_bus_close(sd_bus *bus) {
1174
1175         if (!bus)
1176                 return;
1177         if (bus->state == BUS_CLOSED)
1178                 return;
1179         if (bus_pid_changed(bus))
1180                 return;
1181
1182         bus->state = BUS_CLOSED;
1183
1184         sd_bus_detach_event(bus);
1185
1186         /* Drop all queued messages so that they drop references to
1187          * the bus object and the bus may be freed */
1188         bus_reset_queues(bus);
1189
1190         if (!bus->is_kernel)
1191                 bus_close_fds(bus);
1192
1193         /* We'll leave the fd open in case this is a kernel bus, since
1194          * there might still be memblocks around that reference this
1195          * bus, and they might need to invoke the * KDBUS_CMD_FREE
1196          * ioctl on the fd when they are freed. */
1197 }
1198
1199 static void bus_enter_closing(sd_bus *bus) {
1200         assert(bus);
1201
1202         if (bus->state != BUS_OPENING &&
1203             bus->state != BUS_AUTHENTICATING &&
1204             bus->state != BUS_HELLO &&
1205             bus->state != BUS_RUNNING)
1206                 return;
1207
1208         bus->state = BUS_CLOSING;
1209 }
1210
1211 _public_ sd_bus *sd_bus_ref(sd_bus *bus) {
1212         assert_return(bus, NULL);
1213
1214         assert_se(REFCNT_INC(bus->n_ref) >= 2);
1215
1216         return bus;
1217 }
1218
1219 _public_ sd_bus *sd_bus_unref(sd_bus *bus) {
1220
1221         if (!bus)
1222                 return NULL;
1223
1224         if (REFCNT_DEC(bus->n_ref) <= 0)
1225                 bus_free(bus);
1226
1227         return NULL;
1228 }
1229
1230 _public_ int sd_bus_is_open(sd_bus *bus) {
1231
1232         assert_return(bus, -EINVAL);
1233         assert_return(!bus_pid_changed(bus), -ECHILD);
1234
1235         return BUS_IS_OPEN(bus->state);
1236 }
1237
1238 _public_ int sd_bus_can_send(sd_bus *bus, char type) {
1239         int r;
1240
1241         assert_return(bus, -EINVAL);
1242         assert_return(bus->state != BUS_UNSET, -ENOTCONN);
1243         assert_return(!bus_pid_changed(bus), -ECHILD);
1244
1245         if (type == SD_BUS_TYPE_UNIX_FD) {
1246                 if (!(bus->hello_flags & KDBUS_HELLO_ACCEPT_FD))
1247                         return 0;
1248
1249                 r = bus_ensure_running(bus);
1250                 if (r < 0)
1251                         return r;
1252
1253                 return bus->can_fds;
1254         }
1255
1256         return bus_type_is_valid(type);
1257 }
1258
1259 _public_ int sd_bus_get_server_id(sd_bus *bus, sd_id128_t *server_id) {
1260         int r;
1261
1262         assert_return(bus, -EINVAL);
1263         assert_return(server_id, -EINVAL);
1264         assert_return(!bus_pid_changed(bus), -ECHILD);
1265
1266         r = bus_ensure_running(bus);
1267         if (r < 0)
1268                 return r;
1269
1270         *server_id = bus->server_id;
1271         return 0;
1272 }
1273
1274 static int bus_seal_message(sd_bus *b, sd_bus_message *m, usec_t timeout) {
1275         assert(b);
1276         assert(m);
1277
1278         if (b->message_version != 0 &&
1279             m->header->version != b->message_version)
1280                 return -EPERM;
1281
1282         if (b->message_endian != 0 &&
1283             m->header->endian != b->message_endian)
1284                 return -EPERM;
1285
1286         if (m->sealed) {
1287                 /* If we copy the same message to multiple
1288                  * destinations, avoid using the same serial
1289                  * numbers. */
1290                 b->serial = MAX(b->serial, BUS_MESSAGE_SERIAL(m));
1291                 return 0;
1292         }
1293
1294         if (timeout == 0)
1295                 timeout = BUS_DEFAULT_TIMEOUT;
1296
1297         return bus_message_seal(m, ++b->serial, timeout);
1298 }
1299
1300 int bus_seal_synthetic_message(sd_bus *b, sd_bus_message *m) {
1301         assert(b);
1302         assert(m);
1303
1304         /* The bus specification says the serial number cannot be 0,
1305          * hence let's fill something in for synthetic messages. Since
1306          * synthetic messages might have a fake sender and we don't
1307          * want to interfere with the real sender's serial numbers we
1308          * pick a fixed, artifical one. We use (uint32_t) -1 rather
1309          * than (uint64_t) -1 since dbus1 only had 32bit identifiers,
1310          * even though kdbus can do 64bit. */
1311
1312         return bus_message_seal(m, 0xFFFFFFFFULL, 0);
1313 }
1314
1315 static int bus_write_message(sd_bus *bus, sd_bus_message *message, size_t *idx) {
1316         assert(bus);
1317         assert(message);
1318
1319         if (bus->is_kernel)
1320                 return bus_kernel_write_message(bus, message);
1321         else
1322                 return bus_socket_write_message(bus, message, idx);
1323 }
1324
1325 static int dispatch_wqueue(sd_bus *bus) {
1326         int r, ret = 0;
1327
1328         assert(bus);
1329         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1330
1331         while (bus->wqueue_size > 0) {
1332
1333                 r = bus_write_message(bus, bus->wqueue[0], &bus->windex);
1334                 if (r < 0)
1335                         return r;
1336                 else if (r == 0)
1337                         /* Didn't do anything this time */
1338                         return ret;
1339                 else if (bus->is_kernel || bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
1340                         /* Fully written. Let's drop the entry from
1341                          * the queue.
1342                          *
1343                          * This isn't particularly optimized, but
1344                          * well, this is supposed to be our worst-case
1345                          * buffer only, and the socket buffer is
1346                          * supposed to be our primary buffer, and if
1347                          * it got full, then all bets are off
1348                          * anyway. */
1349
1350                         sd_bus_message_unref(bus->wqueue[0]);
1351                         bus->wqueue_size --;
1352                         memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
1353                         bus->windex = 0;
1354
1355                         ret = 1;
1356                 }
1357         }
1358
1359         return ret;
1360 }
1361
1362 static int bus_read_message(sd_bus *bus) {
1363         assert(bus);
1364
1365         if (bus->is_kernel)
1366                 return bus_kernel_read_message(bus);
1367         else
1368                 return bus_socket_read_message(bus);
1369 }
1370
1371 int bus_rqueue_make_room(sd_bus *bus) {
1372         sd_bus_message **q;
1373         unsigned x;
1374
1375         x = bus->rqueue_size + 1;
1376
1377         if (bus->rqueue_allocated >= x)
1378                 return 0;
1379
1380         if (x > BUS_RQUEUE_MAX)
1381                 return -ENOBUFS;
1382
1383         q = realloc(bus->rqueue, x * sizeof(sd_bus_message*));
1384         if (!q)
1385                 return -ENOMEM;
1386
1387         bus->rqueue = q;
1388         bus->rqueue_allocated = x;
1389
1390         return 0;
1391 }
1392
1393 static int dispatch_rqueue(sd_bus *bus, sd_bus_message **m) {
1394         int r, ret = 0;
1395
1396         assert(bus);
1397         assert(m);
1398         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
1399
1400         for (;;) {
1401                 if (bus->rqueue_size > 0) {
1402                         /* Dispatch a queued message */
1403
1404                         *m = bus->rqueue[0];
1405                         bus->rqueue_size --;
1406                         memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
1407                         return 1;
1408                 }
1409
1410                 /* Try to read a new message */
1411                 r = bus_read_message(bus);
1412                 if (r < 0)
1413                         return r;
1414                 if (r == 0)
1415                         return ret;
1416
1417                 ret = 1;
1418         }
1419 }
1420
1421 _public_ int sd_bus_send(sd_bus *bus, sd_bus_message *m, uint64_t *serial) {
1422         int r;
1423
1424         assert_return(bus, -EINVAL);
1425         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1426         assert_return(m, -EINVAL);
1427         assert_return(!bus_pid_changed(bus), -ECHILD);
1428
1429         if (m->n_fds > 0) {
1430                 r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
1431                 if (r < 0)
1432                         return r;
1433                 if (r == 0)
1434                         return -ENOTSUP;
1435         }
1436
1437         /* If the serial number isn't kept, then we know that no reply
1438          * is expected */
1439         if (!serial && !m->sealed)
1440                 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1441
1442         r = bus_seal_message(bus, m, 0);
1443         if (r < 0)
1444                 return r;
1445
1446         /* If this is a reply and no reply was requested, then let's
1447          * suppress this, if we can */
1448         if (m->dont_send && !serial)
1449                 return 1;
1450
1451         if ((bus->state == BUS_RUNNING || bus->state == BUS_HELLO) && bus->wqueue_size <= 0) {
1452                 size_t idx = 0;
1453
1454                 r = bus_write_message(bus, m, &idx);
1455                 if (r < 0) {
1456                         if (r == -EPIPE || r == -ENOTCONN || r == -ESHUTDOWN)
1457                                 bus_enter_closing(bus);
1458
1459                         return r;
1460                 } else if (!bus->is_kernel && idx < BUS_MESSAGE_SIZE(m))  {
1461                         /* Wasn't fully written. So let's remember how
1462                          * much was written. Note that the first entry
1463                          * of the wqueue array is always allocated so
1464                          * that we always can remember how much was
1465                          * written. */
1466                         bus->wqueue[0] = sd_bus_message_ref(m);
1467                         bus->wqueue_size = 1;
1468                         bus->windex = idx;
1469                 }
1470         } else {
1471                 sd_bus_message **q;
1472
1473                 /* Just append it to the queue. */
1474
1475                 if (bus->wqueue_size >= BUS_WQUEUE_MAX)
1476                         return -ENOBUFS;
1477
1478                 q = realloc(bus->wqueue, sizeof(sd_bus_message*) * (bus->wqueue_size + 1));
1479                 if (!q)
1480                         return -ENOMEM;
1481
1482                 bus->wqueue = q;
1483                 q[bus->wqueue_size ++] = sd_bus_message_ref(m);
1484         }
1485
1486         if (serial)
1487                 *serial = BUS_MESSAGE_SERIAL(m);
1488
1489         return 1;
1490 }
1491
1492 _public_ int sd_bus_send_to(sd_bus *bus, sd_bus_message *m, const char *destination, uint64_t *serial) {
1493         int r;
1494
1495         assert_return(bus, -EINVAL);
1496         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1497         assert_return(m, -EINVAL);
1498         assert_return(!bus_pid_changed(bus), -ECHILD);
1499
1500         if (!streq_ptr(m->destination, destination)) {
1501
1502                 if (!destination)
1503                         return -EEXIST;
1504
1505                 r = sd_bus_message_set_destination(m, destination);
1506                 if (r < 0)
1507                         return r;
1508         }
1509
1510         return sd_bus_send(bus, m, serial);
1511 }
1512
1513 static usec_t calc_elapse(uint64_t usec) {
1514         if (usec == (uint64_t) -1)
1515                 return 0;
1516
1517         return now(CLOCK_MONOTONIC) + usec;
1518 }
1519
1520 static int timeout_compare(const void *a, const void *b) {
1521         const struct reply_callback *x = a, *y = b;
1522
1523         if (x->timeout != 0 && y->timeout == 0)
1524                 return -1;
1525
1526         if (x->timeout == 0 && y->timeout != 0)
1527                 return 1;
1528
1529         if (x->timeout < y->timeout)
1530                 return -1;
1531
1532         if (x->timeout > y->timeout)
1533                 return 1;
1534
1535         return 0;
1536 }
1537
1538 _public_ int sd_bus_call_async(
1539                 sd_bus *bus,
1540                 sd_bus_message *m,
1541                 sd_bus_message_handler_t callback,
1542                 void *userdata,
1543                 uint64_t usec,
1544                 uint64_t *serial) {
1545
1546         struct reply_callback *c;
1547         int r;
1548
1549         assert_return(bus, -EINVAL);
1550         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1551         assert_return(m, -EINVAL);
1552         assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1553         assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1554         assert_return(callback, -EINVAL);
1555         assert_return(!bus_pid_changed(bus), -ECHILD);
1556
1557         r = hashmap_ensure_allocated(&bus->reply_callbacks, uint64_hash_func, uint64_compare_func);
1558         if (r < 0)
1559                 return r;
1560
1561         r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
1562         if (r < 0)
1563                 return r;
1564
1565         r = bus_seal_message(bus, m, usec);
1566         if (r < 0)
1567                 return r;
1568
1569         c = new0(struct reply_callback, 1);
1570         if (!c)
1571                 return -ENOMEM;
1572
1573         c->callback = callback;
1574         c->userdata = userdata;
1575         c->serial = BUS_MESSAGE_SERIAL(m);
1576         c->timeout = calc_elapse(m->timeout);
1577
1578         r = hashmap_put(bus->reply_callbacks, &c->serial, c);
1579         if (r < 0) {
1580                 free(c);
1581                 return r;
1582         }
1583
1584         if (c->timeout != 0) {
1585                 r = prioq_put(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1586                 if (r < 0) {
1587                         c->timeout = 0;
1588                         sd_bus_call_async_cancel(bus, c->serial);
1589                         return r;
1590                 }
1591         }
1592
1593         r = sd_bus_send(bus, m, serial);
1594         if (r < 0) {
1595                 sd_bus_call_async_cancel(bus, c->serial);
1596                 return r;
1597         }
1598
1599         return r;
1600 }
1601
1602 _public_ int sd_bus_call_async_cancel(sd_bus *bus, uint64_t serial) {
1603         struct reply_callback *c;
1604
1605         assert_return(bus, -EINVAL);
1606         assert_return(serial != 0, -EINVAL);
1607         assert_return(!bus_pid_changed(bus), -ECHILD);
1608
1609         c = hashmap_remove(bus->reply_callbacks, &serial);
1610         if (!c)
1611                 return 0;
1612
1613         if (c->timeout != 0)
1614                 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1615
1616         free(c);
1617         return 1;
1618 }
1619
1620 int bus_ensure_running(sd_bus *bus) {
1621         int r;
1622
1623         assert(bus);
1624
1625         if (bus->state == BUS_UNSET || bus->state == BUS_CLOSED || bus->state == BUS_CLOSING)
1626                 return -ENOTCONN;
1627         if (bus->state == BUS_RUNNING)
1628                 return 1;
1629
1630         for (;;) {
1631                 r = sd_bus_process(bus, NULL);
1632                 if (r < 0)
1633                         return r;
1634                 if (bus->state == BUS_RUNNING)
1635                         return 1;
1636                 if (r > 0)
1637                         continue;
1638
1639                 r = sd_bus_wait(bus, (uint64_t) -1);
1640                 if (r < 0)
1641                         return r;
1642         }
1643 }
1644
1645 _public_ int sd_bus_call(
1646                 sd_bus *bus,
1647                 sd_bus_message *m,
1648                 uint64_t usec,
1649                 sd_bus_error *error,
1650                 sd_bus_message **reply) {
1651
1652         usec_t timeout;
1653         uint64_t serial;
1654         unsigned i;
1655         int r;
1656
1657         assert_return(bus, -EINVAL);
1658         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
1659         assert_return(m, -EINVAL);
1660         assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1661         assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL);
1662         assert_return(!bus_error_is_dirty(error), -EINVAL);
1663         assert_return(!bus_pid_changed(bus), -ECHILD);
1664
1665         r = bus_ensure_running(bus);
1666         if (r < 0)
1667                 return r;
1668
1669         i = bus->rqueue_size;
1670
1671         r = bus_seal_message(bus, m, usec);
1672         if (r < 0)
1673                 return r;
1674
1675         r = sd_bus_send(bus, m, &serial);
1676         if (r < 0)
1677                 return r;
1678
1679         timeout = calc_elapse(m->timeout);
1680
1681         for (;;) {
1682                 usec_t left;
1683
1684                 while (i < bus->rqueue_size) {
1685                         sd_bus_message *incoming = NULL;
1686
1687                         incoming = bus->rqueue[i];
1688
1689                         if (incoming->reply_serial == serial) {
1690                                 /* Found a match! */
1691
1692                                 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1693                                 bus->rqueue_size--;
1694
1695                                 if (incoming->header->type == SD_BUS_MESSAGE_METHOD_RETURN) {
1696
1697                                         if (reply)
1698                                                 *reply = incoming;
1699                                         else
1700                                                 sd_bus_message_unref(incoming);
1701
1702                                         return 1;
1703                                 } else if (incoming->header->type == SD_BUS_MESSAGE_METHOD_ERROR)
1704                                         r = sd_bus_error_copy(error, &incoming->error);
1705                                 else
1706                                         r = -EIO;
1707
1708                                 sd_bus_message_unref(incoming);
1709                                 return r;
1710
1711                         } else if (incoming->header->serial == serial &&
1712                                    bus->unique_name &&
1713                                    incoming->sender &&
1714                                    streq(bus->unique_name, incoming->sender)) {
1715
1716                                 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
1717                                 bus->rqueue_size--;
1718
1719                                 /* Our own message? Somebody is trying
1720                                  * to send its own client a message,
1721                                  * let's not dead-lock, let's fail
1722                                  * immediately. */
1723
1724                                 sd_bus_message_unref(incoming);
1725                                 return -ELOOP;
1726                         }
1727
1728                         /* Try to read more, right-away */
1729                         i++;
1730                 }
1731
1732                 r = bus_read_message(bus);
1733                 if (r < 0) {
1734                         if (r == -EPIPE || r == -ENOTCONN || r == -ESHUTDOWN)
1735                                 bus_enter_closing(bus);
1736
1737                         return r;
1738                 }
1739                 if (r > 0)
1740                         continue;
1741
1742                 if (timeout > 0) {
1743                         usec_t n;
1744
1745                         n = now(CLOCK_MONOTONIC);
1746                         if (n >= timeout)
1747                                 return -ETIMEDOUT;
1748
1749                         left = timeout - n;
1750                 } else
1751                         left = (uint64_t) -1;
1752
1753                 r = bus_poll(bus, true, left);
1754                 if (r < 0)
1755                         return r;
1756                 if (r == 0)
1757                         return -ETIMEDOUT;
1758
1759                 r = dispatch_wqueue(bus);
1760                 if (r < 0) {
1761                         if (r == -EPIPE || r == -ENOTCONN || r == -ESHUTDOWN)
1762                                 bus_enter_closing(bus);
1763
1764                         return r;
1765                 }
1766         }
1767 }
1768
1769 _public_ int sd_bus_get_fd(sd_bus *bus) {
1770
1771         assert_return(bus, -EINVAL);
1772         assert_return(bus->input_fd == bus->output_fd, -EPERM);
1773         assert_return(!bus_pid_changed(bus), -ECHILD);
1774
1775         return bus->input_fd;
1776 }
1777
1778 _public_ int sd_bus_get_events(sd_bus *bus) {
1779         int flags = 0;
1780
1781         assert_return(bus, -EINVAL);
1782         assert_return(BUS_IS_OPEN(bus->state) || bus->state == BUS_CLOSING, -ENOTCONN);
1783         assert_return(!bus_pid_changed(bus), -ECHILD);
1784
1785         if (bus->state == BUS_OPENING)
1786                 flags |= POLLOUT;
1787         else if (bus->state == BUS_AUTHENTICATING) {
1788
1789                 if (bus_socket_auth_needs_write(bus))
1790                         flags |= POLLOUT;
1791
1792                 flags |= POLLIN;
1793
1794         } else if (bus->state == BUS_RUNNING || bus->state == BUS_HELLO) {
1795                 if (bus->rqueue_size <= 0)
1796                         flags |= POLLIN;
1797                 if (bus->wqueue_size > 0)
1798                         flags |= POLLOUT;
1799         }
1800
1801         return flags;
1802 }
1803
1804 _public_ int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
1805         struct reply_callback *c;
1806
1807         assert_return(bus, -EINVAL);
1808         assert_return(timeout_usec, -EINVAL);
1809         assert_return(BUS_IS_OPEN(bus->state) || bus->state == BUS_CLOSING, -ENOTCONN);
1810         assert_return(!bus_pid_changed(bus), -ECHILD);
1811
1812         if (bus->state == BUS_CLOSING) {
1813                 *timeout_usec = 0;
1814                 return 1;
1815         }
1816
1817         if (bus->state == BUS_AUTHENTICATING) {
1818                 *timeout_usec = bus->auth_timeout;
1819                 return 1;
1820         }
1821
1822         if (bus->state != BUS_RUNNING && bus->state != BUS_HELLO) {
1823                 *timeout_usec = (uint64_t) -1;
1824                 return 0;
1825         }
1826
1827         if (bus->rqueue_size > 0) {
1828                 *timeout_usec = 0;
1829                 return 1;
1830         }
1831
1832         c = prioq_peek(bus->reply_callbacks_prioq);
1833         if (!c) {
1834                 *timeout_usec = (uint64_t) -1;
1835                 return 0;
1836         }
1837
1838         *timeout_usec = c->timeout;
1839         return 1;
1840 }
1841
1842 static int process_timeout(sd_bus *bus) {
1843         _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
1844         _cleanup_bus_message_unref_ sd_bus_message* m = NULL;
1845         struct reply_callback *c;
1846         usec_t n;
1847         int r;
1848
1849         assert(bus);
1850
1851         c = prioq_peek(bus->reply_callbacks_prioq);
1852         if (!c)
1853                 return 0;
1854
1855         n = now(CLOCK_MONOTONIC);
1856         if (c->timeout > n)
1857                 return 0;
1858
1859         r = bus_message_new_synthetic_error(
1860                         bus,
1861                         c->serial,
1862                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
1863                         &m);
1864         if (r < 0)
1865                 return r;
1866
1867         m->sender = "org.freedesktop.DBus";
1868
1869         r = bus_seal_synthetic_message(bus, m);
1870         if (r < 0)
1871                 return r;
1872
1873         assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
1874         hashmap_remove(bus->reply_callbacks, &c->serial);
1875
1876         bus->current = m;
1877         bus->iteration_counter ++;
1878
1879         r = c->callback(bus, m, c->userdata, &error_buffer);
1880         r = bus_maybe_reply_error(m, r, &error_buffer);
1881         free(c);
1882
1883         bus->current = NULL;
1884
1885         return r;
1886 }
1887
1888 static int process_hello(sd_bus *bus, sd_bus_message *m) {
1889         assert(bus);
1890         assert(m);
1891
1892         if (bus->state != BUS_HELLO)
1893                 return 0;
1894
1895         /* Let's make sure the first message on the bus is the HELLO
1896          * reply. But note that we don't actually parse the message
1897          * here (we leave that to the usual handling), we just verify
1898          * we don't let any earlier msg through. */
1899
1900         if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
1901             m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
1902                 return -EIO;
1903
1904         if (m->reply_serial != bus->hello_serial)
1905                 return -EIO;
1906
1907         return 0;
1908 }
1909
1910 static int process_reply(sd_bus *bus, sd_bus_message *m) {
1911         _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
1912         struct reply_callback *c;
1913         int r;
1914
1915         assert(bus);
1916         assert(m);
1917
1918         if (m->header->type != SD_BUS_MESSAGE_METHOD_RETURN &&
1919             m->header->type != SD_BUS_MESSAGE_METHOD_ERROR)
1920                 return 0;
1921
1922         c = hashmap_remove(bus->reply_callbacks, &m->reply_serial);
1923         if (!c)
1924                 return 0;
1925
1926         if (c->timeout != 0)
1927                 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
1928
1929         r = sd_bus_message_rewind(m, true);
1930         if (r < 0)
1931                 return r;
1932
1933         r = c->callback(bus, m, c->userdata, &error_buffer);
1934         r = bus_maybe_reply_error(m, r, &error_buffer);
1935         free(c);
1936
1937         return r;
1938 }
1939
1940 static int process_filter(sd_bus *bus, sd_bus_message *m) {
1941         _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
1942         struct filter_callback *l;
1943         int r;
1944
1945         assert(bus);
1946         assert(m);
1947
1948         do {
1949                 bus->filter_callbacks_modified = false;
1950
1951                 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
1952
1953                         if (bus->filter_callbacks_modified)
1954                                 break;
1955
1956                         /* Don't run this more than once per iteration */
1957                         if (l->last_iteration == bus->iteration_counter)
1958                                 continue;
1959
1960                         l->last_iteration = bus->iteration_counter;
1961
1962                         r = sd_bus_message_rewind(m, true);
1963                         if (r < 0)
1964                                 return r;
1965
1966                         r = l->callback(bus, m, l->userdata, &error_buffer);
1967                         r = bus_maybe_reply_error(m, r, &error_buffer);
1968                         if (r != 0)
1969                                 return r;
1970
1971                 }
1972
1973         } while (bus->filter_callbacks_modified);
1974
1975         return 0;
1976 }
1977
1978 static int process_match(sd_bus *bus, sd_bus_message *m) {
1979         int r;
1980
1981         assert(bus);
1982         assert(m);
1983
1984         do {
1985                 bus->match_callbacks_modified = false;
1986
1987                 r = bus_match_run(bus, &bus->match_callbacks, m);
1988                 if (r != 0)
1989                         return r;
1990
1991         } while (bus->match_callbacks_modified);
1992
1993         return 0;
1994 }
1995
1996 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
1997         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
1998         int r;
1999
2000         assert(bus);
2001         assert(m);
2002
2003         if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2004                 return 0;
2005
2006         if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2007                 return 0;
2008
2009         if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2010                 return 1;
2011
2012         if (streq_ptr(m->member, "Ping"))
2013                 r = sd_bus_message_new_method_return(m, &reply);
2014         else if (streq_ptr(m->member, "GetMachineId")) {
2015                 sd_id128_t id;
2016                 char sid[33];
2017
2018                 r = sd_id128_get_machine(&id);
2019                 if (r < 0)
2020                         return r;
2021
2022                 r = sd_bus_message_new_method_return(m, &reply);
2023                 if (r < 0)
2024                         return r;
2025
2026                 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2027         } else {
2028                 r = sd_bus_message_new_method_errorf(
2029                                 m, &reply,
2030                                 SD_BUS_ERROR_UNKNOWN_METHOD,
2031                                  "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2032         }
2033
2034         if (r < 0)
2035                 return r;
2036
2037         r = sd_bus_send(bus, reply, NULL);
2038         if (r < 0)
2039                 return r;
2040
2041         return 1;
2042 }
2043
2044 static int process_message(sd_bus *bus, sd_bus_message *m) {
2045         int r;
2046
2047         assert(bus);
2048         assert(m);
2049
2050         bus->current = m;
2051         bus->iteration_counter++;
2052
2053         log_debug("Got message sender=%s object=%s interface=%s member=%s",
2054                   strna(sd_bus_message_get_sender(m)),
2055                   strna(sd_bus_message_get_path(m)),
2056                   strna(sd_bus_message_get_interface(m)),
2057                   strna(sd_bus_message_get_member(m)));
2058
2059         r = process_hello(bus, m);
2060         if (r != 0)
2061                 goto finish;
2062
2063         r = process_reply(bus, m);
2064         if (r != 0)
2065                 goto finish;
2066
2067         r = process_filter(bus, m);
2068         if (r != 0)
2069                 goto finish;
2070
2071         r = process_match(bus, m);
2072         if (r != 0)
2073                 goto finish;
2074
2075         r = process_builtin(bus, m);
2076         if (r != 0)
2077                 goto finish;
2078
2079         r = bus_process_object(bus, m);
2080
2081 finish:
2082         bus->current = NULL;
2083         return r;
2084 }
2085
2086 static int process_running(sd_bus *bus, sd_bus_message **ret) {
2087         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2088         int r;
2089
2090         assert(bus);
2091         assert(bus->state == BUS_RUNNING || bus->state == BUS_HELLO);
2092
2093         r = process_timeout(bus);
2094         if (r != 0)
2095                 goto null_message;
2096
2097         r = dispatch_wqueue(bus);
2098         if (r != 0)
2099                 goto null_message;
2100
2101         r = dispatch_rqueue(bus, &m);
2102         if (r < 0)
2103                 return r;
2104         if (!m)
2105                 goto null_message;
2106
2107         r = process_message(bus, m);
2108         if (r != 0)
2109                 goto null_message;
2110
2111         if (ret) {
2112                 r = sd_bus_message_rewind(m, true);
2113                 if (r < 0)
2114                         return r;
2115
2116                 *ret = m;
2117                 m = NULL;
2118                 return 1;
2119         }
2120
2121         if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2122
2123                 r = sd_bus_reply_method_errorf(
2124                                 m,
2125                                 SD_BUS_ERROR_UNKNOWN_OBJECT,
2126                                 "Unknown object '%s'.", m->path);
2127                 if (r < 0)
2128                         return r;
2129         }
2130
2131         return 1;
2132
2133 null_message:
2134         if (r >= 0 && ret)
2135                 *ret = NULL;
2136
2137         return r;
2138 }
2139
2140 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2141         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
2142         struct reply_callback *c;
2143         int r;
2144
2145         assert(bus);
2146         assert(bus->state == BUS_CLOSING);
2147
2148         c = hashmap_first(bus->reply_callbacks);
2149         if (c) {
2150                 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2151
2152                 /* First, fail all outstanding method calls */
2153                 r = bus_message_new_synthetic_error(
2154                                 bus,
2155                                 c->serial,
2156                                 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2157                                 &m);
2158                 if (r < 0)
2159                         return r;
2160
2161                 r = bus_seal_synthetic_message(bus, m);
2162                 if (r < 0)
2163                         return r;
2164
2165                 if (c->timeout != 0)
2166                         prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2167
2168                 hashmap_remove(bus->reply_callbacks, &c->serial);
2169
2170                 bus->current = m;
2171                 bus->iteration_counter++;
2172
2173                 r = c->callback(bus, m, c->userdata, &error_buffer);
2174                 r = bus_maybe_reply_error(m, r, &error_buffer);
2175                 free(c);
2176
2177                 goto finish;
2178         }
2179
2180         /* Then, synthesize a Disconnected message */
2181         r = sd_bus_message_new_signal(
2182                         bus,
2183                         "/org/freedesktop/DBus/Local",
2184                         "org.freedesktop.DBus.Local",
2185                         "Disconnected",
2186                         &m);
2187         if (r < 0)
2188                 return r;
2189
2190         m->sender = "org.freedesktop.DBus.Local";
2191
2192         r = bus_seal_synthetic_message(bus, m);
2193         if (r < 0)
2194                 return r;
2195
2196         sd_bus_close(bus);
2197
2198         bus->current = m;
2199         bus->iteration_counter++;
2200
2201         r = process_filter(bus, m);
2202         if (r != 0)
2203                 goto finish;
2204
2205         r = process_match(bus, m);
2206         if (r != 0)
2207                 goto finish;
2208
2209         if (ret) {
2210                 *ret = m;
2211                 m = NULL;
2212         }
2213
2214         r = 1;
2215
2216 finish:
2217         bus->current = NULL;
2218         return r;
2219 }
2220
2221 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2222         BUS_DONT_DESTROY(bus);
2223         int r;
2224
2225         /* Returns 0 when we didn't do anything. This should cause the
2226          * caller to invoke sd_bus_wait() before returning the next
2227          * time. Returns > 0 when we did something, which possibly
2228          * means *ret is filled in with an unprocessed message. */
2229
2230         assert_return(bus, -EINVAL);
2231         assert_return(!bus_pid_changed(bus), -ECHILD);
2232
2233         /* We don't allow recursively invoking sd_bus_process(). */
2234         assert_return(!bus->current, -EBUSY);
2235
2236         switch (bus->state) {
2237
2238         case BUS_UNSET:
2239                 return -ENOTCONN;
2240
2241         case BUS_CLOSED:
2242                 return -ECONNRESET;
2243
2244         case BUS_OPENING:
2245                 r = bus_socket_process_opening(bus);
2246                 if (r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2247                         bus_enter_closing(bus);
2248                         r = 1;
2249                 } else if (r < 0)
2250                         return r;
2251                 if (ret)
2252                         *ret = NULL;
2253                 return r;
2254
2255         case BUS_AUTHENTICATING:
2256                 r = bus_socket_process_authenticating(bus);
2257                 if (r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2258                         bus_enter_closing(bus);
2259                         r = 1;
2260                 } else if (r < 0)
2261                         return r;
2262
2263                 if (ret)
2264                         *ret = NULL;
2265
2266                 return r;
2267
2268         case BUS_RUNNING:
2269         case BUS_HELLO:
2270                 r = process_running(bus, ret);
2271                 if (r == -ECONNRESET || r == -EPIPE || r == -ESHUTDOWN) {
2272                         bus_enter_closing(bus);
2273                         r = 1;
2274
2275                         if (ret)
2276                                 *ret = NULL;
2277                 }
2278
2279                 return r;
2280
2281         case BUS_CLOSING:
2282                 return process_closing(bus, ret);
2283         }
2284
2285         assert_not_reached("Unknown state");
2286 }
2287
2288 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2289         struct pollfd p[2] = {};
2290         int r, e, n;
2291         struct timespec ts;
2292         usec_t m = (usec_t) -1;
2293
2294         assert(bus);
2295
2296         if (bus->state == BUS_CLOSING)
2297                 return 1;
2298
2299         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2300
2301         e = sd_bus_get_events(bus);
2302         if (e < 0)
2303                 return e;
2304
2305         if (need_more)
2306                 /* The caller really needs some more data, he doesn't
2307                  * care about what's already read, or any timeouts
2308                  * except its own.*/
2309                 e |= POLLIN;
2310         else {
2311                 usec_t until;
2312                 /* The caller wants to process if there's something to
2313                  * process, but doesn't care otherwise */
2314
2315                 r = sd_bus_get_timeout(bus, &until);
2316                 if (r < 0)
2317                         return r;
2318                 if (r > 0) {
2319                         usec_t nw;
2320                         nw = now(CLOCK_MONOTONIC);
2321                         m = until > nw ? until - nw : 0;
2322                 }
2323         }
2324
2325         if (timeout_usec != (uint64_t) -1 && (m == (uint64_t) -1 || timeout_usec < m))
2326                 m = timeout_usec;
2327
2328         p[0].fd = bus->input_fd;
2329         if (bus->output_fd == bus->input_fd) {
2330                 p[0].events = e;
2331                 n = 1;
2332         } else {
2333                 p[0].events = e & POLLIN;
2334                 p[1].fd = bus->output_fd;
2335                 p[1].events = e & POLLOUT;
2336                 n = 2;
2337         }
2338
2339         r = ppoll(p, n, m == (uint64_t) -1 ? NULL : timespec_store(&ts, m), NULL);
2340         if (r < 0)
2341                 return -errno;
2342
2343         return r > 0 ? 1 : 0;
2344 }
2345
2346 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
2347
2348         assert_return(bus, -EINVAL);
2349         assert_return(!bus_pid_changed(bus), -ECHILD);
2350
2351         if (bus->state == BUS_CLOSING)
2352                 return 0;
2353
2354         assert_return(BUS_IS_OPEN(bus->state) , -ENOTCONN);
2355
2356         if (bus->rqueue_size > 0)
2357                 return 0;
2358
2359         return bus_poll(bus, false, timeout_usec);
2360 }
2361
2362 _public_ int sd_bus_flush(sd_bus *bus) {
2363         int r;
2364
2365         assert_return(bus, -EINVAL);
2366         assert_return(!bus_pid_changed(bus), -ECHILD);
2367
2368         if (bus->state == BUS_CLOSING)
2369                 return 0;
2370
2371         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2372
2373         r = bus_ensure_running(bus);
2374         if (r < 0)
2375                 return r;
2376
2377         if (bus->wqueue_size <= 0)
2378                 return 0;
2379
2380         for (;;) {
2381                 r = dispatch_wqueue(bus);
2382                 if (r < 0) {
2383                         if (r == -EPIPE || r == -ENOTCONN || r == -ESHUTDOWN)
2384                                 bus_enter_closing(bus);
2385
2386                         return r;
2387                 }
2388
2389                 if (bus->wqueue_size <= 0)
2390                         return 0;
2391
2392                 r = bus_poll(bus, false, (uint64_t) -1);
2393                 if (r < 0)
2394                         return r;
2395         }
2396 }
2397
2398 _public_ int sd_bus_add_filter(sd_bus *bus,
2399                                sd_bus_message_handler_t callback,
2400                                void *userdata) {
2401
2402         struct filter_callback *f;
2403
2404         assert_return(bus, -EINVAL);
2405         assert_return(callback, -EINVAL);
2406         assert_return(!bus_pid_changed(bus), -ECHILD);
2407
2408         f = new0(struct filter_callback, 1);
2409         if (!f)
2410                 return -ENOMEM;
2411         f->callback = callback;
2412         f->userdata = userdata;
2413
2414         bus->filter_callbacks_modified = true;
2415         LIST_PREPEND(callbacks, bus->filter_callbacks, f);
2416         return 0;
2417 }
2418
2419 _public_ int sd_bus_remove_filter(sd_bus *bus,
2420                                   sd_bus_message_handler_t callback,
2421                                   void *userdata) {
2422
2423         struct filter_callback *f;
2424
2425         assert_return(bus, -EINVAL);
2426         assert_return(callback, -EINVAL);
2427         assert_return(!bus_pid_changed(bus), -ECHILD);
2428
2429         LIST_FOREACH(callbacks, f, bus->filter_callbacks) {
2430                 if (f->callback == callback && f->userdata == userdata) {
2431                         bus->filter_callbacks_modified = true;
2432                         LIST_REMOVE(callbacks, bus->filter_callbacks, f);
2433                         free(f);
2434                         return 1;
2435                 }
2436         }
2437
2438         return 0;
2439 }
2440
2441 _public_ int sd_bus_add_match(sd_bus *bus,
2442                               const char *match,
2443                               sd_bus_message_handler_t callback,
2444                               void *userdata) {
2445
2446         struct bus_match_component *components = NULL;
2447         unsigned n_components = 0;
2448         uint64_t cookie = 0;
2449         int r = 0;
2450
2451         assert_return(bus, -EINVAL);
2452         assert_return(match, -EINVAL);
2453         assert_return(!bus_pid_changed(bus), -ECHILD);
2454
2455         r = bus_match_parse(match, &components, &n_components);
2456         if (r < 0)
2457                 goto finish;
2458
2459         if (bus->bus_client) {
2460                 cookie = ++bus->match_cookie;
2461
2462                 r = bus_add_match_internal(bus, match, components, n_components, cookie);
2463                 if (r < 0)
2464                         goto finish;
2465         }
2466
2467         bus->match_callbacks_modified = true;
2468         r = bus_match_add(&bus->match_callbacks, components, n_components, callback, userdata, cookie, NULL);
2469         if (r < 0) {
2470                 if (bus->bus_client)
2471                         bus_remove_match_internal(bus, match, cookie);
2472         }
2473
2474 finish:
2475         bus_match_parse_free(components, n_components);
2476         return r;
2477 }
2478
2479 _public_ int sd_bus_remove_match(sd_bus *bus,
2480                                  const char *match,
2481                                  sd_bus_message_handler_t callback,
2482                                  void *userdata) {
2483
2484         struct bus_match_component *components = NULL;
2485         unsigned n_components = 0;
2486         int r = 0, q = 0;
2487         uint64_t cookie = 0;
2488
2489         assert_return(bus, -EINVAL);
2490         assert_return(match, -EINVAL);
2491         assert_return(!bus_pid_changed(bus), -ECHILD);
2492
2493         r = bus_match_parse(match, &components, &n_components);
2494         if (r < 0)
2495                 return r;
2496
2497         bus->match_callbacks_modified = true;
2498         r = bus_match_remove(&bus->match_callbacks, components, n_components, callback, userdata, &cookie);
2499
2500         if (bus->bus_client)
2501                 q = bus_remove_match_internal(bus, match, cookie);
2502
2503         bus_match_parse_free(components, n_components);
2504
2505         return r < 0 ? r : q;
2506 }
2507
2508 bool bus_pid_changed(sd_bus *bus) {
2509         assert(bus);
2510
2511         /* We don't support people creating a bus connection and
2512          * keeping it around over a fork(). Let's complain. */
2513
2514         return bus->original_pid != getpid();
2515 }
2516
2517 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
2518         sd_bus *bus = userdata;
2519         int r;
2520
2521         assert(bus);
2522
2523         r = sd_bus_process(bus, NULL);
2524         if (r < 0)
2525                 return r;
2526
2527         return 1;
2528 }
2529
2530 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
2531         sd_bus *bus = userdata;
2532         int r;
2533
2534         assert(bus);
2535
2536         r = sd_bus_process(bus, NULL);
2537         if (r < 0)
2538                 return r;
2539
2540         return 1;
2541 }
2542
2543 static int prepare_callback(sd_event_source *s, void *userdata) {
2544         sd_bus *bus = userdata;
2545         int r, e;
2546         usec_t until;
2547
2548         assert(s);
2549         assert(bus);
2550
2551         e = sd_bus_get_events(bus);
2552         if (e < 0)
2553                 return e;
2554
2555         if (bus->output_fd != bus->input_fd) {
2556
2557                 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
2558                 if (r < 0)
2559                         return r;
2560
2561                 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
2562                 if (r < 0)
2563                         return r;
2564         } else {
2565                 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
2566                 if (r < 0)
2567                         return r;
2568         }
2569
2570         r = sd_bus_get_timeout(bus, &until);
2571         if (r < 0)
2572                 return r;
2573         if (r > 0) {
2574                 int j;
2575
2576                 j = sd_event_source_set_time(bus->time_event_source, until);
2577                 if (j < 0)
2578                         return j;
2579         }
2580
2581         r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
2582         if (r < 0)
2583                 return r;
2584
2585         return 1;
2586 }
2587
2588 static int quit_callback(sd_event_source *event, void *userdata) {
2589         sd_bus *bus = userdata;
2590
2591         assert(event);
2592
2593         sd_bus_flush(bus);
2594
2595         return 1;
2596 }
2597
2598 static int attach_io_events(sd_bus *bus) {
2599         int r;
2600
2601         assert(bus);
2602
2603         if (bus->input_fd < 0)
2604                 return 0;
2605
2606         if (!bus->event)
2607                 return 0;
2608
2609         if (!bus->input_io_event_source) {
2610                 r = sd_event_add_io(bus->event, bus->input_fd, 0, io_callback, bus, &bus->input_io_event_source);
2611                 if (r < 0)
2612                         return r;
2613
2614                 r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
2615                 if (r < 0)
2616                         return r;
2617
2618                 r = sd_event_source_set_priority(bus->input_io_event_source, bus->event_priority);
2619         } else
2620                 r = sd_event_source_set_io_fd(bus->input_io_event_source, bus->input_fd);
2621
2622         if (r < 0)
2623                 return r;
2624
2625         if (bus->output_fd != bus->input_fd) {
2626                 assert(bus->output_fd >= 0);
2627
2628                 if (!bus->output_io_event_source) {
2629                         r = sd_event_add_io(bus->event, bus->output_fd, 0, io_callback, bus, &bus->output_io_event_source);
2630                         if (r < 0)
2631                                 return r;
2632
2633                         r = sd_event_source_set_priority(bus->output_io_event_source, bus->event_priority);
2634                 } else
2635                         r = sd_event_source_set_io_fd(bus->output_io_event_source, bus->output_fd);
2636
2637                 if (r < 0)
2638                         return r;
2639         }
2640
2641         return 0;
2642 }
2643
2644 static void detach_io_events(sd_bus *bus) {
2645         assert(bus);
2646
2647         if (bus->input_io_event_source) {
2648                 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
2649                 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
2650         }
2651
2652         if (bus->output_io_event_source) {
2653                 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
2654                 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
2655         }
2656 }
2657
2658 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
2659         int r;
2660
2661         assert_return(bus, -EINVAL);
2662         assert_return(!bus->event, -EBUSY);
2663
2664         assert(!bus->input_io_event_source);
2665         assert(!bus->output_io_event_source);
2666         assert(!bus->time_event_source);
2667
2668         if (event)
2669                 bus->event = sd_event_ref(event);
2670         else  {
2671                 r = sd_event_default(&bus->event);
2672                 if (r < 0)
2673                         return r;
2674         }
2675
2676         bus->event_priority = priority;
2677
2678         r = sd_event_add_monotonic(bus->event, 0, 0, time_callback, bus, &bus->time_event_source);
2679         if (r < 0)
2680                 goto fail;
2681
2682         r = sd_event_source_set_priority(bus->time_event_source, priority);
2683         if (r < 0)
2684                 goto fail;
2685
2686         r = sd_event_add_exit(bus->event, quit_callback, bus, &bus->quit_event_source);
2687         if (r < 0)
2688                 goto fail;
2689
2690         r = attach_io_events(bus);
2691         if (r < 0)
2692                 goto fail;
2693
2694         return 0;
2695
2696 fail:
2697         sd_bus_detach_event(bus);
2698         return r;
2699 }
2700
2701 _public_ int sd_bus_detach_event(sd_bus *bus) {
2702         assert_return(bus, -EINVAL);
2703
2704         if (!bus->event)
2705                 return 0;
2706
2707         detach_io_events(bus);
2708
2709         if (bus->time_event_source) {
2710                 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
2711                 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
2712         }
2713
2714         if (bus->quit_event_source) {
2715                 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
2716                 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
2717         }
2718
2719         if (bus->event)
2720                 bus->event = sd_event_unref(bus->event);
2721
2722         return 1;
2723 }
2724
2725 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
2726         assert_return(bus, NULL);
2727
2728         return bus->event;
2729 }
2730
2731 _public_ sd_bus_message* sd_bus_get_current(sd_bus *bus) {
2732         assert_return(bus, NULL);
2733
2734         return bus->current;
2735 }
2736
2737 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
2738         sd_bus *b = NULL;
2739         int r;
2740
2741         assert(bus_open);
2742         assert(default_bus);
2743
2744         if (!ret)
2745                 return !!*default_bus;
2746
2747         if (*default_bus) {
2748                 *ret = sd_bus_ref(*default_bus);
2749                 return 0;
2750         }
2751
2752         r = bus_open(&b);
2753         if (r < 0)
2754                 return r;
2755
2756         b->default_bus_ptr = default_bus;
2757         b->tid = gettid();
2758         *default_bus = b;
2759
2760         *ret = b;
2761         return 1;
2762 }
2763
2764 _public_ int sd_bus_default_system(sd_bus **ret) {
2765         static __thread sd_bus *default_system_bus = NULL;
2766
2767         return bus_default(sd_bus_open_system, &default_system_bus, ret);
2768 }
2769
2770 _public_ int sd_bus_default_user(sd_bus **ret) {
2771         static __thread sd_bus *default_user_bus = NULL;
2772
2773         return bus_default(sd_bus_open_user, &default_user_bus, ret);
2774 }
2775
2776 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
2777         assert_return(b, -EINVAL);
2778         assert_return(tid, -EINVAL);
2779         assert_return(!bus_pid_changed(b), -ECHILD);
2780
2781         if (b->tid != 0) {
2782                 *tid = b->tid;
2783                 return 0;
2784         }
2785
2786         if (b->event)
2787                 return sd_event_get_tid(b->event, tid);
2788
2789         return -ENXIO;
2790 }
2791
2792 _public_ char *sd_bus_label_escape(const char *s) {
2793         char *r, *t;
2794         const char *f;
2795
2796         assert_return(s, NULL);
2797
2798         /* Escapes all chars that D-Bus' object path cannot deal
2799          * with. Can be reversed with bus_path_unescape(). We special
2800          * case the empty string. */
2801
2802         if (*s == 0)
2803                 return strdup("_");
2804
2805         r = new(char, strlen(s)*3 + 1);
2806         if (!r)
2807                 return NULL;
2808
2809         for (f = s, t = r; *f; f++) {
2810
2811                 /* Escape everything that is not a-zA-Z0-9. We also
2812                  * escape 0-9 if it's the first character */
2813
2814                 if (!(*f >= 'A' && *f <= 'Z') &&
2815                     !(*f >= 'a' && *f <= 'z') &&
2816                     !(f > s && *f >= '0' && *f <= '9')) {
2817                         *(t++) = '_';
2818                         *(t++) = hexchar(*f >> 4);
2819                         *(t++) = hexchar(*f);
2820                 } else
2821                         *(t++) = *f;
2822         }
2823
2824         *t = 0;
2825
2826         return r;
2827 }
2828
2829 _public_ char *sd_bus_label_unescape(const char *f) {
2830         char *r, *t;
2831
2832         assert_return(f, NULL);
2833
2834         /* Special case for the empty string */
2835         if (streq(f, "_"))
2836                 return strdup("");
2837
2838         r = new(char, strlen(f) + 1);
2839         if (!r)
2840                 return NULL;
2841
2842         for (t = r; *f; f++) {
2843
2844                 if (*f == '_') {
2845                         int a, b;
2846
2847                         if ((a = unhexchar(f[1])) < 0 ||
2848                             (b = unhexchar(f[2])) < 0) {
2849                                 /* Invalid escape code, let's take it literal then */
2850                                 *(t++) = '_';
2851                         } else {
2852                                 *(t++) = (char) ((a << 4) | b);
2853                                 f += 2;
2854                         }
2855                 } else
2856                         *(t++) = *f;
2857         }
2858
2859         *t = 0;
2860
2861         return r;
2862 }
2863
2864 _public_ int sd_bus_get_peer_creds(sd_bus *bus, uint64_t mask, sd_bus_creds **ret) {
2865         sd_bus_creds *c;
2866         pid_t pid = 0;
2867         int r;
2868
2869         assert_return(bus, -EINVAL);
2870         assert_return(mask <= _SD_BUS_CREDS_ALL, -ENOTSUP);
2871         assert_return(ret, -EINVAL);
2872         assert_return(BUS_IS_OPEN(bus->state), -ENOTCONN);
2873         assert_return(!bus_pid_changed(bus), -ECHILD);
2874         assert_return(!bus->is_kernel, -ENOTSUP);
2875
2876         if (!bus->ucred_valid && !isempty(bus->label))
2877                 return -ENODATA;
2878
2879         c = bus_creds_new();
2880         if (!c)
2881                 return -ENOMEM;
2882
2883         if (bus->ucred_valid) {
2884                 pid = c->pid = bus->ucred.pid;
2885                 c->uid = bus->ucred.uid;
2886                 c->gid = bus->ucred.gid;
2887
2888                 c->mask |= (SD_BUS_CREDS_UID | SD_BUS_CREDS_PID | SD_BUS_CREDS_GID) & mask;
2889         }
2890
2891         if (!isempty(bus->label) && (mask & SD_BUS_CREDS_SELINUX_CONTEXT)) {
2892                 c->label = strdup(bus->label);
2893                 if (!c->label) {
2894                         sd_bus_creds_unref(c);
2895                         return -ENOMEM;
2896                 }
2897
2898                 c->mask |= SD_BUS_CREDS_SELINUX_CONTEXT;
2899         }
2900
2901         r = bus_creds_add_more(c, mask, pid, 0);
2902         if (r < 0)
2903                 return r;
2904
2905         *ret = c;
2906         return 0;
2907 }