chiark / gitweb /
220fcdcf52bdd782d26df65a21604101749f20f2
[elogind.git] / src / libelogind / sd-bus / sd-bus.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   This file is part of systemd.
4
5   Copyright 2013 Lennart Poettering
6 ***/
7
8 #include <endian.h>
9 #include <netdb.h>
10 #include <poll.h>
11 #include <pthread.h>
12 //#include <signal.h>
13 #include <stdlib.h>
14 #include <sys/mman.h>
15 //#include <sys/wait.h>
16 #include <unistd.h>
17
18 #include "sd-bus.h"
19
20 #include "alloc-util.h"
21 #include "bus-container.h"
22 #include "bus-control.h"
23 #include "bus-internal.h"
24 #include "bus-kernel.h"
25 #include "bus-label.h"
26 #include "bus-message.h"
27 #include "bus-objects.h"
28 #include "bus-protocol.h"
29 #include "bus-slot.h"
30 #include "bus-socket.h"
31 #include "bus-track.h"
32 #include "bus-type.h"
33 #include "bus-util.h"
34 #include "cgroup-util.h"
35 #include "def.h"
36 #include "fd-util.h"
37 #include "hexdecoct.h"
38 #include "hostname-util.h"
39 #include "macro.h"
40 #include "missing.h"
41 #include "parse-util.h"
42 //#include "process-util.h"
43 #include "string-util.h"
44 #include "strv.h"
45 #include "util.h"
46
47 /// Additional includes needed by elogind
48 #include "process-util.h"
49
50 #define log_debug_bus_message(m)                                         \
51         do {                                                             \
52                 sd_bus_message *_mm = (m);                               \
53                 log_debug("Got message type=%s sender=%s destination=%s path=%s interface=%s member=%s cookie=%" PRIu64 " reply_cookie=%" PRIu64 " signature=%s error-name=%s error-message=%s", \
54                           bus_message_type_to_string(_mm->header->type), \
55                           strna(sd_bus_message_get_sender(_mm)),         \
56                           strna(sd_bus_message_get_destination(_mm)),    \
57                           strna(sd_bus_message_get_path(_mm)),           \
58                           strna(sd_bus_message_get_interface(_mm)),      \
59                           strna(sd_bus_message_get_member(_mm)),         \
60                           BUS_MESSAGE_COOKIE(_mm),                       \
61                           _mm->reply_cookie,                             \
62                           strna(_mm->root_container.signature),          \
63                           strna(_mm->error.name),                        \
64                           strna(_mm->error.message));                    \
65         } while (false)
66
67 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec);
68 static void bus_detach_io_events(sd_bus *b);
69 static void bus_detach_inotify_event(sd_bus *b);
70
71 static thread_local sd_bus *default_system_bus = NULL;
72 static thread_local sd_bus *default_user_bus = NULL;
73 static thread_local sd_bus *default_starter_bus = NULL;
74
75 static sd_bus **bus_choose_default(int (**bus_open)(sd_bus **)) {
76         const char *e;
77
78         /* Let's try our best to reuse another cached connection. If
79          * the starter bus type is set, connect via our normal
80          * connection logic, ignoring $DBUS_STARTER_ADDRESS, so that
81          * we can share the connection with the user/system default
82          * bus. */
83
84         e = secure_getenv("DBUS_STARTER_BUS_TYPE");
85         if (e) {
86                 if (streq(e, "system")) {
87                         if (bus_open)
88                                 *bus_open = sd_bus_open_system;
89                         return &default_system_bus;
90                 } else if (STR_IN_SET(e, "user", "session")) {
91                         if (bus_open)
92                                 *bus_open = sd_bus_open_user;
93                         return &default_user_bus;
94                 }
95         }
96
97         /* No type is specified, so we have not other option than to
98          * use the starter address if it is set. */
99         e = secure_getenv("DBUS_STARTER_ADDRESS");
100         if (e) {
101                 if (bus_open)
102                         *bus_open = sd_bus_open;
103                 return &default_starter_bus;
104         }
105
106         /* Finally, if nothing is set use the cached connection for
107          * the right scope */
108
109         if (cg_pid_get_owner_uid(0, NULL) >= 0) {
110                 if (bus_open)
111                         *bus_open = sd_bus_open_user;
112                 return &default_user_bus;
113         } else {
114                 if (bus_open)
115                         *bus_open = sd_bus_open_system;
116                 return &default_system_bus;
117         }
118 }
119
120 sd_bus *bus_resolve(sd_bus *bus) {
121         switch ((uintptr_t) bus) {
122         case (uintptr_t) SD_BUS_DEFAULT:
123                 return *(bus_choose_default(NULL));
124         case (uintptr_t) SD_BUS_DEFAULT_USER:
125                 return default_user_bus;
126         case (uintptr_t) SD_BUS_DEFAULT_SYSTEM:
127                 return default_system_bus;
128         default:
129                 return bus;
130         }
131 }
132
133 void bus_close_io_fds(sd_bus *b) {
134         assert(b);
135
136         bus_detach_io_events(b);
137
138         if (b->input_fd != b->output_fd)
139                 safe_close(b->output_fd);
140         b->output_fd = b->input_fd = safe_close(b->input_fd);
141 }
142
143 void bus_close_inotify_fd(sd_bus *b) {
144         assert(b);
145
146         bus_detach_inotify_event(b);
147
148         b->inotify_fd = safe_close(b->inotify_fd);
149         b->inotify_watches = mfree(b->inotify_watches);
150         b->n_inotify_watches = 0;
151 }
152
153 static void bus_reset_queues(sd_bus *b) {
154         assert(b);
155
156         while (b->rqueue_size > 0)
157                 sd_bus_message_unref(b->rqueue[--b->rqueue_size]);
158
159         b->rqueue = mfree(b->rqueue);
160         b->rqueue_allocated = 0;
161
162         while (b->wqueue_size > 0)
163                 sd_bus_message_unref(b->wqueue[--b->wqueue_size]);
164
165         b->wqueue = mfree(b->wqueue);
166         b->wqueue_allocated = 0;
167 }
168
169 static sd_bus* bus_free(sd_bus *b) {
170         sd_bus_slot *s;
171
172         assert(b);
173         assert(!b->track_queue);
174         assert(!b->tracks);
175
176         b->state = BUS_CLOSED;
177
178         sd_bus_detach_event(b);
179
180         while ((s = b->slots)) {
181                 /* At this point only floating slots can still be
182                  * around, because the non-floating ones keep a
183                  * reference to the bus, and we thus couldn't be
184                  * destructing right now... We forcibly disconnect the
185                  * slots here, so that they still can be referenced by
186                  * apps, but are dead. */
187
188                 assert(s->floating);
189                 bus_slot_disconnect(s);
190                 sd_bus_slot_unref(s);
191         }
192
193         if (b->default_bus_ptr)
194                 *b->default_bus_ptr = NULL;
195
196         bus_close_io_fds(b);
197         bus_close_inotify_fd(b);
198
199         free(b->label);
200         free(b->groups);
201         free(b->rbuffer);
202         free(b->unique_name);
203         free(b->auth_buffer);
204         free(b->address);
205         free(b->machine);
206         free(b->cgroup_root);
207         free(b->description);
208         free(b->patch_sender);
209
210         free(b->exec_path);
211         strv_free(b->exec_argv);
212
213         close_many(b->fds, b->n_fds);
214         free(b->fds);
215
216         bus_reset_queues(b);
217
218         ordered_hashmap_free_free(b->reply_callbacks);
219         prioq_free(b->reply_callbacks_prioq);
220
221         assert(b->match_callbacks.type == BUS_MATCH_ROOT);
222         bus_match_free(&b->match_callbacks);
223
224         hashmap_free_free(b->vtable_methods);
225         hashmap_free_free(b->vtable_properties);
226
227         assert(hashmap_isempty(b->nodes));
228         hashmap_free(b->nodes);
229
230         bus_flush_memfd(b);
231
232         assert_se(pthread_mutex_destroy(&b->memfd_cache_mutex) == 0);
233
234         return mfree(b);
235 }
236
237 DEFINE_TRIVIAL_CLEANUP_FUNC(sd_bus*, bus_free);
238
239 _public_ int sd_bus_new(sd_bus **ret) {
240         _cleanup_free_ sd_bus *b = NULL;
241
242         assert_return(ret, -EINVAL);
243
244         b = new0(sd_bus, 1);
245         if (!b)
246                 return -ENOMEM;
247
248         b->n_ref = REFCNT_INIT;
249         b->input_fd = b->output_fd = -1;
250         b->inotify_fd = -1;
251         b->message_version = 1;
252         b->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
253         b->accept_fd = true;
254         b->original_pid = getpid_cached();
255         b->n_groups = (size_t) -1;
256
257         assert_se(pthread_mutex_init(&b->memfd_cache_mutex, NULL) == 0);
258
259         /* We guarantee that wqueue always has space for at least one entry */
260         if (!GREEDY_REALLOC(b->wqueue, b->wqueue_allocated, 1))
261                 return -ENOMEM;
262
263         *ret = TAKE_PTR(b);
264         return 0;
265 }
266
267 _public_ int sd_bus_set_address(sd_bus *bus, const char *address) {
268         assert_return(bus, -EINVAL);
269         assert_return(bus = bus_resolve(bus), -ENOPKG);
270         assert_return(bus->state == BUS_UNSET, -EPERM);
271         assert_return(address, -EINVAL);
272         assert_return(!bus_pid_changed(bus), -ECHILD);
273
274         return free_and_strdup(&bus->address, address);
275 }
276
277 _public_ int sd_bus_set_fd(sd_bus *bus, int input_fd, int output_fd) {
278         assert_return(bus, -EINVAL);
279         assert_return(bus = bus_resolve(bus), -ENOPKG);
280         assert_return(bus->state == BUS_UNSET, -EPERM);
281         assert_return(input_fd >= 0, -EBADF);
282         assert_return(output_fd >= 0, -EBADF);
283         assert_return(!bus_pid_changed(bus), -ECHILD);
284
285         bus->input_fd = input_fd;
286         bus->output_fd = output_fd;
287         return 0;
288 }
289
290 _public_ int sd_bus_set_exec(sd_bus *bus, const char *path, char *const argv[]) {
291         _cleanup_strv_free_ char **a = NULL;
292         int r;
293
294         assert_return(bus, -EINVAL);
295         assert_return(bus = bus_resolve(bus), -ENOPKG);
296         assert_return(bus->state == BUS_UNSET, -EPERM);
297         assert_return(path, -EINVAL);
298         assert_return(!strv_isempty(argv), -EINVAL);
299         assert_return(!bus_pid_changed(bus), -ECHILD);
300
301         a = strv_copy(argv);
302         if (!a)
303                 return -ENOMEM;
304
305         r = free_and_strdup(&bus->exec_path, path);
306         if (r < 0)
307                 return r;
308
309         return strv_free_and_replace(bus->exec_argv, a);
310 }
311
312 _public_ int sd_bus_set_bus_client(sd_bus *bus, int b) {
313         assert_return(bus, -EINVAL);
314         assert_return(bus = bus_resolve(bus), -ENOPKG);
315         assert_return(bus->state == BUS_UNSET, -EPERM);
316         assert_return(!bus->patch_sender, -EPERM);
317         assert_return(!bus_pid_changed(bus), -ECHILD);
318
319         bus->bus_client = !!b;
320         return 0;
321 }
322
323 _public_ int sd_bus_set_monitor(sd_bus *bus, int b) {
324         assert_return(bus, -EINVAL);
325         assert_return(bus = bus_resolve(bus), -ENOPKG);
326         assert_return(bus->state == BUS_UNSET, -EPERM);
327         assert_return(!bus_pid_changed(bus), -ECHILD);
328
329         bus->is_monitor = !!b;
330         return 0;
331 }
332
333 _public_ int sd_bus_negotiate_fds(sd_bus *bus, int b) {
334         assert_return(bus, -EINVAL);
335         assert_return(bus = bus_resolve(bus), -ENOPKG);
336         assert_return(bus->state == BUS_UNSET, -EPERM);
337         assert_return(!bus_pid_changed(bus), -ECHILD);
338
339         bus->accept_fd = !!b;
340         return 0;
341 }
342
343 _public_ int sd_bus_negotiate_timestamp(sd_bus *bus, int b) {
344         assert_return(bus, -EINVAL);
345         assert_return(bus = bus_resolve(bus), -ENOPKG);
346         assert_return(!IN_SET(bus->state, BUS_CLOSING, BUS_CLOSED), -EPERM);
347         assert_return(!bus_pid_changed(bus), -ECHILD);
348
349         /* This is not actually supported by any of our transports these days, but we do honour it for synthetic
350          * replies, and maybe one day classic D-Bus learns this too */
351         bus->attach_timestamp = !!b;
352
353         return 0;
354 }
355
356 _public_ int sd_bus_negotiate_creds(sd_bus *bus, int b, uint64_t mask) {
357         assert_return(bus, -EINVAL);
358         assert_return(bus = bus_resolve(bus), -ENOPKG);
359         assert_return(mask <= _SD_BUS_CREDS_ALL, -EINVAL);
360         assert_return(!IN_SET(bus->state, BUS_CLOSING, BUS_CLOSED), -EPERM);
361         assert_return(!bus_pid_changed(bus), -ECHILD);
362
363         SET_FLAG(bus->creds_mask, mask, b);
364
365         /* The well knowns we need unconditionally, so that matches can work */
366         bus->creds_mask |= SD_BUS_CREDS_WELL_KNOWN_NAMES|SD_BUS_CREDS_UNIQUE_NAME;
367
368         return 0;
369 }
370
371 _public_ int sd_bus_set_server(sd_bus *bus, int b, sd_id128_t server_id) {
372         assert_return(bus, -EINVAL);
373         assert_return(bus = bus_resolve(bus), -ENOPKG);
374         assert_return(b || sd_id128_equal(server_id, SD_ID128_NULL), -EINVAL);
375         assert_return(bus->state == BUS_UNSET, -EPERM);
376         assert_return(!bus_pid_changed(bus), -ECHILD);
377
378         bus->is_server = !!b;
379         bus->server_id = server_id;
380         return 0;
381 }
382
383 _public_ int sd_bus_set_anonymous(sd_bus *bus, int b) {
384         assert_return(bus, -EINVAL);
385         assert_return(bus = bus_resolve(bus), -ENOPKG);
386         assert_return(bus->state == BUS_UNSET, -EPERM);
387         assert_return(!bus_pid_changed(bus), -ECHILD);
388
389         bus->anonymous_auth = !!b;
390         return 0;
391 }
392
393 _public_ int sd_bus_set_trusted(sd_bus *bus, int b) {
394         assert_return(bus, -EINVAL);
395         assert_return(bus = bus_resolve(bus), -ENOPKG);
396         assert_return(bus->state == BUS_UNSET, -EPERM);
397         assert_return(!bus_pid_changed(bus), -ECHILD);
398
399         bus->trusted = !!b;
400         return 0;
401 }
402
403 _public_ int sd_bus_set_description(sd_bus *bus, const char *description) {
404         assert_return(bus, -EINVAL);
405         assert_return(bus = bus_resolve(bus), -ENOPKG);
406         assert_return(bus->state == BUS_UNSET, -EPERM);
407         assert_return(!bus_pid_changed(bus), -ECHILD);
408
409         return free_and_strdup(&bus->description, description);
410 }
411
412 _public_ int sd_bus_set_allow_interactive_authorization(sd_bus *bus, int b) {
413         assert_return(bus, -EINVAL);
414         assert_return(bus = bus_resolve(bus), -ENOPKG);
415         assert_return(!bus_pid_changed(bus), -ECHILD);
416
417         bus->allow_interactive_authorization = !!b;
418         return 0;
419 }
420
421 _public_ int sd_bus_get_allow_interactive_authorization(sd_bus *bus) {
422         assert_return(bus, -EINVAL);
423         assert_return(bus = bus_resolve(bus), -ENOPKG);
424         assert_return(!bus_pid_changed(bus), -ECHILD);
425
426         return bus->allow_interactive_authorization;
427 }
428
429 _public_ int sd_bus_set_watch_bind(sd_bus *bus, int b) {
430         assert_return(bus, -EINVAL);
431         assert_return(bus = bus_resolve(bus), -ENOPKG);
432         assert_return(bus->state == BUS_UNSET, -EPERM);
433         assert_return(!bus_pid_changed(bus), -ECHILD);
434
435         bus->watch_bind = !!b;
436         return 0;
437 }
438
439 _public_ int sd_bus_get_watch_bind(sd_bus *bus) {
440         assert_return(bus, -EINVAL);
441         assert_return(bus = bus_resolve(bus), -ENOPKG);
442         assert_return(!bus_pid_changed(bus), -ECHILD);
443
444         return bus->watch_bind;
445 }
446
447 _public_ int sd_bus_set_connected_signal(sd_bus *bus, int b) {
448         assert_return(bus, -EINVAL);
449         assert_return(bus = bus_resolve(bus), -ENOPKG);
450         assert_return(bus->state == BUS_UNSET, -EPERM);
451         assert_return(!bus_pid_changed(bus), -ECHILD);
452
453         bus->connected_signal = !!b;
454         return 0;
455 }
456
457 _public_ int sd_bus_get_connected_signal(sd_bus *bus) {
458         assert_return(bus, -EINVAL);
459         assert_return(bus = bus_resolve(bus), -ENOPKG);
460         assert_return(!bus_pid_changed(bus), -ECHILD);
461
462         return bus->connected_signal;
463 }
464
465 static int synthesize_connected_signal(sd_bus *bus) {
466         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
467         int r;
468
469         assert(bus);
470
471         /* If enabled, synthesizes a local "Connected" signal mirroring the local "Disconnected" signal. This is called
472          * whenever we fully established a connection, i.e. after the authorization phase, and after receiving the
473          * Hello() reply. Or in other words, whenver we enter BUS_RUNNING state.
474          *
475          * This is useful so that clients can start doing stuff whenver the connection is fully established in a way
476          * that works independently from whether we connected to a full bus or just a direct connection. */
477
478         if (!bus->connected_signal)
479                 return 0;
480
481         r = sd_bus_message_new_signal(
482                         bus,
483                         &m,
484                         "/org/freedesktop/DBus/Local",
485                         "org.freedesktop.DBus.Local",
486                         "Connected");
487         if (r < 0)
488                 return r;
489
490         bus_message_set_sender_local(bus, m);
491
492         r = bus_seal_synthetic_message(bus, m);
493         if (r < 0)
494                 return r;
495
496         r = bus_rqueue_make_room(bus);
497         if (r < 0)
498                 return r;
499
500         /* Insert at the very front */
501         memmove(bus->rqueue + 1, bus->rqueue, sizeof(sd_bus_message*) * bus->rqueue_size);
502         bus->rqueue[0] = TAKE_PTR(m);
503         bus->rqueue_size++;
504
505         return 0;
506 }
507
508 void bus_set_state(sd_bus *bus, enum bus_state state) {
509
510         static const char * const table[_BUS_STATE_MAX] = {
511                 [BUS_UNSET] = "UNSET",
512                 [BUS_WATCH_BIND] = "WATCH_BIND",
513                 [BUS_OPENING] = "OPENING",
514                 [BUS_AUTHENTICATING] = "AUTHENTICATING",
515                 [BUS_HELLO] = "HELLO",
516                 [BUS_RUNNING] = "RUNNING",
517                 [BUS_CLOSING] = "CLOSING",
518                 [BUS_CLOSED] = "CLOSED",
519         };
520
521         assert(bus);
522         assert(state < _BUS_STATE_MAX);
523
524         if (state == bus->state)
525                 return;
526
527         log_debug("Bus %s: changing state %s â†’ %s", strna(bus->description), table[bus->state], table[state]);
528         bus->state = state;
529 }
530
531 static int hello_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
532         const char *s;
533         sd_bus *bus;
534         int r;
535
536         assert(reply);
537         bus = reply->bus;
538         assert(bus);
539         assert(IN_SET(bus->state, BUS_HELLO, BUS_CLOSING));
540
541         r = sd_bus_message_get_errno(reply);
542         if (r > 0)
543                 return -r;
544
545         r = sd_bus_message_read(reply, "s", &s);
546         if (r < 0)
547                 return r;
548
549         if (!service_name_is_valid(s) || s[0] != ':')
550                 return -EBADMSG;
551
552         r = free_and_strdup(&bus->unique_name, s);
553         if (r < 0)
554                 return r;
555
556         if (bus->state == BUS_HELLO) {
557                 bus_set_state(bus, BUS_RUNNING);
558
559                 r = synthesize_connected_signal(bus);
560                 if (r < 0)
561                         return r;
562         }
563
564         return 1;
565 }
566
567 static int bus_send_hello(sd_bus *bus) {
568         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
569         int r;
570
571         assert(bus);
572
573         if (!bus->bus_client)
574                 return 0;
575
576         r = sd_bus_message_new_method_call(
577                         bus,
578                         &m,
579                         "org.freedesktop.DBus",
580                         "/org/freedesktop/DBus",
581                         "org.freedesktop.DBus",
582                         "Hello");
583         if (r < 0)
584                 return r;
585
586         return sd_bus_call_async(bus, NULL, m, hello_callback, NULL, 0);
587 }
588
589 int bus_start_running(sd_bus *bus) {
590         struct reply_callback *c;
591         Iterator i;
592         usec_t n;
593         int r;
594
595         assert(bus);
596         assert(bus->state < BUS_HELLO);
597
598         /* We start all method call timeouts when we enter BUS_HELLO or BUS_RUNNING mode. At this point let's convert
599          * all relative to absolute timestamps. Note that we do not reshuffle the reply callback priority queue since
600          * adding a fixed value to all entries should not alter the internal order. */
601
602         n = now(CLOCK_MONOTONIC);
603         ORDERED_HASHMAP_FOREACH(c, bus->reply_callbacks, i) {
604                 if (c->timeout_usec == 0)
605                         continue;
606
607                 c->timeout_usec = usec_add(n, c->timeout_usec);
608         }
609
610         if (bus->bus_client) {
611                 bus_set_state(bus, BUS_HELLO);
612                 return 1;
613         }
614
615         bus_set_state(bus, BUS_RUNNING);
616
617         r = synthesize_connected_signal(bus);
618         if (r < 0)
619                 return r;
620
621         return 1;
622 }
623
624 static int parse_address_key(const char **p, const char *key, char **value) {
625         size_t l, n = 0, allocated = 0;
626         _cleanup_free_ char *r = NULL;
627         const char *a;
628
629         assert(p);
630         assert(*p);
631         assert(value);
632
633         if (key) {
634                 l = strlen(key);
635                 if (strncmp(*p, key, l) != 0)
636                         return 0;
637
638                 if ((*p)[l] != '=')
639                         return 0;
640
641                 if (*value)
642                         return -EINVAL;
643
644                 a = *p + l + 1;
645         } else
646                 a = *p;
647
648         while (!IN_SET(*a, ';', ',', 0)) {
649                 char c;
650
651                 if (*a == '%') {
652                         int x, y;
653
654                         x = unhexchar(a[1]);
655                         if (x < 0)
656                                 return x;
657
658                         y = unhexchar(a[2]);
659                         if (y < 0)
660                                 return y;
661
662                         c = (char) ((x << 4) | y);
663                         a += 3;
664                 } else {
665                         c = *a;
666                         a++;
667                 }
668
669                 if (!GREEDY_REALLOC(r, allocated, n + 2))
670                         return -ENOMEM;
671
672                 r[n++] = c;
673         }
674
675         if (!r) {
676                 r = strdup("");
677                 if (!r)
678                         return -ENOMEM;
679         } else
680                 r[n] = 0;
681
682         if (*a == ',')
683                 a++;
684
685         *p = a;
686
687         free_and_replace(*value, r);
688
689         return 1;
690 }
691
692 static void skip_address_key(const char **p) {
693         assert(p);
694         assert(*p);
695
696         *p += strcspn(*p, ",");
697
698         if (**p == ',')
699                 (*p)++;
700 }
701
702 static int parse_unix_address(sd_bus *b, const char **p, char **guid) {
703         _cleanup_free_ char *path = NULL, *abstract = NULL;
704         size_t l;
705         int r;
706
707         assert(b);
708         assert(p);
709         assert(*p);
710         assert(guid);
711
712         while (!IN_SET(**p, 0, ';')) {
713                 r = parse_address_key(p, "guid", guid);
714                 if (r < 0)
715                         return r;
716                 else if (r > 0)
717                         continue;
718
719                 r = parse_address_key(p, "path", &path);
720                 if (r < 0)
721                         return r;
722                 else if (r > 0)
723                         continue;
724
725                 r = parse_address_key(p, "abstract", &abstract);
726                 if (r < 0)
727                         return r;
728                 else if (r > 0)
729                         continue;
730
731                 skip_address_key(p);
732         }
733
734         if (!path && !abstract)
735                 return -EINVAL;
736
737         if (path && abstract)
738                 return -EINVAL;
739
740         if (path) {
741                 l = strlen(path);
742                 if (l > sizeof(b->sockaddr.un.sun_path))
743                         return -E2BIG;
744
745                 b->sockaddr.un.sun_family = AF_UNIX;
746                 strncpy(b->sockaddr.un.sun_path, path, sizeof(b->sockaddr.un.sun_path));
747                 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + l;
748         } else if (abstract) {
749                 l = strlen(abstract);
750                 if (l > sizeof(b->sockaddr.un.sun_path) - 1)
751                         return -E2BIG;
752
753                 b->sockaddr.un.sun_family = AF_UNIX;
754                 b->sockaddr.un.sun_path[0] = 0;
755                 strncpy(b->sockaddr.un.sun_path+1, abstract, sizeof(b->sockaddr.un.sun_path)-1);
756                 b->sockaddr_size = offsetof(struct sockaddr_un, sun_path) + 1 + l;
757         }
758
759         b->is_local = true;
760
761         return 0;
762 }
763
764 static int parse_tcp_address(sd_bus *b, const char **p, char **guid) {
765         _cleanup_free_ char *host = NULL, *port = NULL, *family = NULL;
766         int r;
767         struct addrinfo *result, hints = {
768                 .ai_socktype = SOCK_STREAM,
769                 .ai_flags = AI_ADDRCONFIG,
770         };
771
772         assert(b);
773         assert(p);
774         assert(*p);
775         assert(guid);
776
777         while (!IN_SET(**p, 0, ';')) {
778                 r = parse_address_key(p, "guid", guid);
779                 if (r < 0)
780                         return r;
781                 else if (r > 0)
782                         continue;
783
784                 r = parse_address_key(p, "host", &host);
785                 if (r < 0)
786                         return r;
787                 else if (r > 0)
788                         continue;
789
790                 r = parse_address_key(p, "port", &port);
791                 if (r < 0)
792                         return r;
793                 else if (r > 0)
794                         continue;
795
796                 r = parse_address_key(p, "family", &family);
797                 if (r < 0)
798                         return r;
799                 else if (r > 0)
800                         continue;
801
802                 skip_address_key(p);
803         }
804
805         if (!host || !port)
806                 return -EINVAL;
807
808         if (family) {
809                 if (streq(family, "ipv4"))
810                         hints.ai_family = AF_INET;
811                 else if (streq(family, "ipv6"))
812                         hints.ai_family = AF_INET6;
813                 else
814                         return -EINVAL;
815         }
816
817         r = getaddrinfo(host, port, &hints, &result);
818         if (r == EAI_SYSTEM)
819                 return -errno;
820         else if (r != 0)
821                 return -EADDRNOTAVAIL;
822
823         memcpy(&b->sockaddr, result->ai_addr, result->ai_addrlen);
824         b->sockaddr_size = result->ai_addrlen;
825
826         freeaddrinfo(result);
827
828         b->is_local = false;
829
830         return 0;
831 }
832
833 static int parse_exec_address(sd_bus *b, const char **p, char **guid) {
834         char *path = NULL;
835         unsigned n_argv = 0, j;
836         char **argv = NULL;
837         size_t allocated = 0;
838         int r;
839
840         assert(b);
841         assert(p);
842         assert(*p);
843         assert(guid);
844
845         while (!IN_SET(**p, 0, ';')) {
846                 r = parse_address_key(p, "guid", guid);
847                 if (r < 0)
848                         goto fail;
849                 else if (r > 0)
850                         continue;
851
852                 r = parse_address_key(p, "path", &path);
853                 if (r < 0)
854                         goto fail;
855                 else if (r > 0)
856                         continue;
857
858                 if (startswith(*p, "argv")) {
859                         unsigned ul;
860
861                         errno = 0;
862                         ul = strtoul(*p + 4, (char**) p, 10);
863                         if (errno > 0 || **p != '=' || ul > 256) {
864                                 r = -EINVAL;
865                                 goto fail;
866                         }
867
868                         (*p)++;
869
870                         if (ul >= n_argv) {
871                                 if (!GREEDY_REALLOC0(argv, allocated, ul + 2)) {
872                                         r = -ENOMEM;
873                                         goto fail;
874                                 }
875
876                                 n_argv = ul + 1;
877                         }
878
879                         r = parse_address_key(p, NULL, argv + ul);
880                         if (r < 0)
881                                 goto fail;
882
883                         continue;
884                 }
885
886                 skip_address_key(p);
887         }
888
889         if (!path) {
890                 r = -EINVAL;
891                 goto fail;
892         }
893
894         /* Make sure there are no holes in the array, with the
895          * exception of argv[0] */
896         for (j = 1; j < n_argv; j++)
897                 if (!argv[j]) {
898                         r = -EINVAL;
899                         goto fail;
900                 }
901
902         if (argv && argv[0] == NULL) {
903                 argv[0] = strdup(path);
904                 if (!argv[0]) {
905                         r = -ENOMEM;
906                         goto fail;
907                 }
908         }
909
910         b->exec_path = path;
911         b->exec_argv = argv;
912
913         b->is_local = false;
914
915         return 0;
916
917 fail:
918         for (j = 0; j < n_argv; j++)
919                 free(argv[j]);
920
921         free(argv);
922         free(path);
923         return r;
924 }
925
926 static int parse_container_unix_address(sd_bus *b, const char **p, char **guid) {
927         _cleanup_free_ char *machine = NULL, *pid = NULL;
928         int r;
929
930         assert(b);
931         assert(p);
932         assert(*p);
933         assert(guid);
934
935         while (!IN_SET(**p, 0, ';')) {
936                 r = parse_address_key(p, "guid", guid);
937                 if (r < 0)
938                         return r;
939                 else if (r > 0)
940                         continue;
941
942                 r = parse_address_key(p, "machine", &machine);
943                 if (r < 0)
944                         return r;
945                 else if (r > 0)
946                         continue;
947
948                 r = parse_address_key(p, "pid", &pid);
949                 if (r < 0)
950                         return r;
951                 else if (r > 0)
952                         continue;
953
954                 skip_address_key(p);
955         }
956
957         if (!machine == !pid)
958                 return -EINVAL;
959
960         if (machine) {
961                 if (!machine_name_is_valid(machine))
962                         return -EINVAL;
963
964                 free_and_replace(b->machine, machine);
965         } else {
966                 b->machine = mfree(b->machine);
967         }
968
969         if (pid) {
970                 r = parse_pid(pid, &b->nspid);
971                 if (r < 0)
972                         return r;
973         } else
974                 b->nspid = 0;
975
976         b->sockaddr.un.sun_family = AF_UNIX;
977         /* Note that we use the old /var/run prefix here, to increase compatibility with really old containers */
978         strncpy(b->sockaddr.un.sun_path, "/var/run/dbus/system_bus_socket", sizeof(b->sockaddr.un.sun_path));
979         b->sockaddr_size = SOCKADDR_UN_LEN(b->sockaddr.un);
980         b->is_local = false;
981
982         return 0;
983 }
984
985 static void bus_reset_parsed_address(sd_bus *b) {
986         assert(b);
987
988         zero(b->sockaddr);
989         b->sockaddr_size = 0;
990         b->exec_argv = strv_free(b->exec_argv);
991         b->exec_path = mfree(b->exec_path);
992         b->server_id = SD_ID128_NULL;
993         b->machine = mfree(b->machine);
994         b->nspid = 0;
995 }
996
997 static int bus_parse_next_address(sd_bus *b) {
998         _cleanup_free_ char *guid = NULL;
999         const char *a;
1000         int r;
1001
1002         assert(b);
1003
1004         if (!b->address)
1005                 return 0;
1006         if (b->address[b->address_index] == 0)
1007                 return 0;
1008
1009         bus_reset_parsed_address(b);
1010
1011         a = b->address + b->address_index;
1012
1013         while (*a != 0) {
1014
1015                 if (*a == ';') {
1016                         a++;
1017                         continue;
1018                 }
1019
1020                 if (startswith(a, "unix:")) {
1021                         a += 5;
1022
1023                         r = parse_unix_address(b, &a, &guid);
1024                         if (r < 0)
1025                                 return r;
1026                         break;
1027
1028                 } else if (startswith(a, "tcp:")) {
1029
1030                         a += 4;
1031                         r = parse_tcp_address(b, &a, &guid);
1032                         if (r < 0)
1033                                 return r;
1034
1035                         break;
1036
1037                 } else if (startswith(a, "unixexec:")) {
1038
1039                         a += 9;
1040                         r = parse_exec_address(b, &a, &guid);
1041                         if (r < 0)
1042                                 return r;
1043
1044                         break;
1045
1046                 } else if (startswith(a, "x-machine-unix:")) {
1047
1048                         a += 15;
1049                         r = parse_container_unix_address(b, &a, &guid);
1050                         if (r < 0)
1051                                 return r;
1052
1053                         break;
1054                 }
1055
1056                 a = strchr(a, ';');
1057                 if (!a)
1058                         return 0;
1059         }
1060
1061         if (guid) {
1062                 r = sd_id128_from_string(guid, &b->server_id);
1063                 if (r < 0)
1064                         return r;
1065         }
1066
1067         b->address_index = a - b->address;
1068         return 1;
1069 }
1070
1071 static void bus_kill_exec(sd_bus *bus) {
1072         if (pid_is_valid(bus->busexec_pid) > 0) {
1073                 sigterm_wait(bus->busexec_pid);
1074                 bus->busexec_pid = 0;
1075         }
1076 }
1077
1078 static int bus_start_address(sd_bus *b) {
1079         int r;
1080
1081         assert(b);
1082
1083         for (;;) {
1084                 bus_close_io_fds(b);
1085                 bus_close_inotify_fd(b);
1086
1087                 bus_kill_exec(b);
1088
1089                 /* If you provide multiple different bus-addresses, we
1090                  * try all of them in order and use the first one that
1091                  * succeeds. */
1092
1093                 if (b->exec_path)
1094                         r = bus_socket_exec(b);
1095                 else if ((b->nspid > 0 || b->machine) && b->sockaddr.sa.sa_family != AF_UNSPEC)
1096                         r = bus_container_connect_socket(b);
1097                 else if (b->sockaddr.sa.sa_family != AF_UNSPEC)
1098                         r = bus_socket_connect(b);
1099                 else
1100                         goto next;
1101
1102                 if (r >= 0) {
1103                         int q;
1104
1105                         q = bus_attach_io_events(b);
1106                         if (q < 0)
1107                                 return q;
1108
1109                         q = bus_attach_inotify_event(b);
1110                         if (q < 0)
1111                                 return q;
1112
1113                         return r;
1114                 }
1115
1116                 b->last_connect_error = -r;
1117
1118         next:
1119                 r = bus_parse_next_address(b);
1120                 if (r < 0)
1121                         return r;
1122                 if (r == 0)
1123                         return b->last_connect_error > 0 ? -b->last_connect_error : -ECONNREFUSED;
1124         }
1125 }
1126
1127 int bus_next_address(sd_bus *b) {
1128         assert(b);
1129
1130         bus_reset_parsed_address(b);
1131         return bus_start_address(b);
1132 }
1133
1134 static int bus_start_fd(sd_bus *b) {
1135         struct stat st;
1136         int r;
1137
1138         assert(b);
1139         assert(b->input_fd >= 0);
1140         assert(b->output_fd >= 0);
1141
1142         r = fd_nonblock(b->input_fd, true);
1143         if (r < 0)
1144                 return r;
1145
1146         r = fd_cloexec(b->input_fd, true);
1147         if (r < 0)
1148                 return r;
1149
1150         if (b->input_fd != b->output_fd) {
1151                 r = fd_nonblock(b->output_fd, true);
1152                 if (r < 0)
1153                         return r;
1154
1155                 r = fd_cloexec(b->output_fd, true);
1156                 if (r < 0)
1157                         return r;
1158         }
1159
1160         if (fstat(b->input_fd, &st) < 0)
1161                 return -errno;
1162
1163         return bus_socket_take_fd(b);
1164 }
1165
1166 _public_ int sd_bus_start(sd_bus *bus) {
1167         int r;
1168
1169         assert_return(bus, -EINVAL);
1170         assert_return(bus = bus_resolve(bus), -ENOPKG);
1171         assert_return(bus->state == BUS_UNSET, -EPERM);
1172         assert_return(!bus_pid_changed(bus), -ECHILD);
1173
1174         bus_set_state(bus, BUS_OPENING);
1175
1176         if (bus->is_server && bus->bus_client)
1177                 return -EINVAL;
1178
1179         if (bus->input_fd >= 0)
1180                 r = bus_start_fd(bus);
1181         else if (bus->address || bus->sockaddr.sa.sa_family != AF_UNSPEC || bus->exec_path || bus->machine)
1182                 r = bus_start_address(bus);
1183         else
1184                 return -EINVAL;
1185
1186         if (r < 0) {
1187                 sd_bus_close(bus);
1188                 return r;
1189         }
1190
1191         return bus_send_hello(bus);
1192 }
1193
1194 _public_ int sd_bus_open_with_description(sd_bus **ret, const char *description) {
1195         const char *e;
1196         _cleanup_(bus_freep) sd_bus *b = NULL;
1197         int r;
1198
1199         assert_return(ret, -EINVAL);
1200
1201         /* Let's connect to the starter bus if it is set, and
1202          * otherwise to the bus that is appropropriate for the scope
1203          * we are running in */
1204
1205         e = secure_getenv("DBUS_STARTER_BUS_TYPE");
1206         if (e) {
1207                 if (streq(e, "system"))
1208                         return sd_bus_open_system_with_description(ret, description);
1209 #if 0 /// elogind does not support systemd user instances
1210                 else if (STR_IN_SET(e, "session", "user"))
1211 #endif // 0
1212                         return sd_bus_open_user_with_description(ret, description);
1213         }
1214
1215         e = secure_getenv("DBUS_STARTER_ADDRESS");
1216         if (!e) {
1217 #if 0 /// elogind does not support systemd user instances
1218                 if (cg_pid_get_owner_uid(0, NULL) >= 0)
1219                         return sd_bus_open_user_with_description(ret, description);
1220                 else
1221 #endif // 0
1222                         return sd_bus_open_system_with_description(ret, description);
1223         }
1224
1225         r = sd_bus_new(&b);
1226         if (r < 0)
1227                 return r;
1228
1229         r = sd_bus_set_address(b, e);
1230         if (r < 0)
1231                 return r;
1232
1233         b->bus_client = true;
1234
1235         /* We don't know whether the bus is trusted or not, so better
1236          * be safe, and authenticate everything */
1237         b->trusted = false;
1238         b->is_local = false;
1239         b->creds_mask |= SD_BUS_CREDS_UID | SD_BUS_CREDS_EUID | SD_BUS_CREDS_EFFECTIVE_CAPS;
1240
1241         r = sd_bus_start(b);
1242         if (r < 0)
1243                 return r;
1244
1245         *ret = TAKE_PTR(b);
1246         return 0;
1247 }
1248
1249 _public_ int sd_bus_open(sd_bus **ret) {
1250         return sd_bus_open_with_description(ret, NULL);
1251 }
1252
1253 int bus_set_address_system(sd_bus *b) {
1254         const char *e;
1255         assert(b);
1256
1257         e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1258         if (e)
1259                 return sd_bus_set_address(b, e);
1260
1261         return sd_bus_set_address(b, DEFAULT_SYSTEM_BUS_ADDRESS);
1262 }
1263
1264 _public_ int sd_bus_open_system_with_description(sd_bus **ret, const char *description) {
1265         _cleanup_(bus_freep) sd_bus *b = NULL;
1266         int r;
1267
1268         assert_return(ret, -EINVAL);
1269
1270         r = sd_bus_new(&b);
1271         if (r < 0)
1272                 return r;
1273
1274         if (description) {
1275                 r = sd_bus_set_description(b, description);
1276                 if (r < 0)
1277                         return r;
1278         }
1279
1280         r = bus_set_address_system(b);
1281         if (r < 0)
1282                 return r;
1283
1284         b->bus_client = true;
1285         b->is_system = true;
1286
1287         /* Let's do per-method access control on the system bus. We
1288          * need the caller's UID and capability set for that. */
1289         b->trusted = false;
1290         b->creds_mask |= SD_BUS_CREDS_UID | SD_BUS_CREDS_EUID | SD_BUS_CREDS_EFFECTIVE_CAPS;
1291         b->is_local = true;
1292
1293         r = sd_bus_start(b);
1294         if (r < 0)
1295                 return r;
1296
1297         *ret = TAKE_PTR(b);
1298         return 0;
1299 }
1300
1301 _public_ int sd_bus_open_system(sd_bus **ret) {
1302         return sd_bus_open_system_with_description(ret, NULL);
1303 }
1304
1305 #if 0 /// elogind can not open/use a user bus
1306 int bus_set_address_user(sd_bus *b) {
1307         const char *e;
1308         _cleanup_free_ char *ee = NULL, *s = NULL;
1309
1310         assert(b);
1311
1312         e = secure_getenv("DBUS_SESSION_BUS_ADDRESS");
1313         if (e)
1314                 return sd_bus_set_address(b, e);
1315
1316         e = secure_getenv("XDG_RUNTIME_DIR");
1317         if (!e)
1318                 return -ENOENT;
1319
1320         ee = bus_address_escape(e);
1321         if (!ee)
1322                 return -ENOMEM;
1323
1324         if (asprintf(&s, DEFAULT_USER_BUS_ADDRESS_FMT, ee) < 0)
1325                 return -ENOMEM;
1326
1327         b->address = TAKE_PTR(s);
1328
1329         return 0;
1330 }
1331 #endif // 0
1332
1333 _public_ int sd_bus_open_user_with_description(sd_bus **ret, const char *description) {
1334 #if 0 /// elogind does not support user buses
1335         _cleanup_(bus_freep) sd_bus *b = NULL;
1336         int r;
1337
1338         assert_return(ret, -EINVAL);
1339
1340         r = sd_bus_new(&b);
1341         if (r < 0)
1342                 return r;
1343
1344         if (description) {
1345                 r = sd_bus_set_description(b, description);
1346                 if (r < 0)
1347                         return r;
1348         }
1349
1350         r = bus_set_address_user(b);
1351         if (r < 0)
1352                 return r;
1353
1354         b->bus_client = true;
1355         b->is_user = true;
1356
1357         /* We don't do any per-method access control on the user
1358          * bus. */
1359         b->trusted = true;
1360         b->is_local = true;
1361
1362         r = sd_bus_start(b);
1363         if (r < 0)
1364                 return r;
1365
1366         *ret = TAKE_PTR(b);
1367         return 0;
1368 }
1369
1370 _public_ int sd_bus_open_user(sd_bus **ret) {
1371         return sd_bus_open_user_with_description(ret, NULL);
1372 #else
1373         return sd_bus_open_system(ret);
1374 #endif // 0
1375 }
1376
1377 int bus_set_address_system_remote(sd_bus *b, const char *host) {
1378         _cleanup_free_ char *e = NULL;
1379         char *m = NULL, *c = NULL, *a;
1380
1381         assert(b);
1382         assert(host);
1383
1384         /* Let's see if we shall enter some container */
1385         m = strchr(host, ':');
1386         if (m) {
1387                 m++;
1388
1389                 /* Let's make sure this is not a port of some kind,
1390                  * and is a valid machine name. */
1391                 if (!in_charset(m, DIGITS) && machine_name_is_valid(m)) {
1392                         char *t;
1393
1394                         /* Cut out the host part */
1395                         t = strndupa(host, m - host - 1);
1396                         e = bus_address_escape(t);
1397                         if (!e)
1398                                 return -ENOMEM;
1399
1400                         c = strjoina(",argv5=--machine=", m);
1401                 }
1402         }
1403
1404         if (!e) {
1405                 e = bus_address_escape(host);
1406                 if (!e)
1407                         return -ENOMEM;
1408         }
1409
1410         a = strjoin("unixexec:path=ssh,argv1=-xT,argv2=--,argv3=", e, ",argv4=elogind-stdio-bridge", c);
1411         if (!a)
1412                 return -ENOMEM;
1413
1414         return free_and_replace(b->address, a);
1415 }
1416
1417 _public_ int sd_bus_open_system_remote(sd_bus **ret, const char *host) {
1418         _cleanup_(bus_freep) sd_bus *b = NULL;
1419         int r;
1420
1421         assert_return(host, -EINVAL);
1422         assert_return(ret, -EINVAL);
1423
1424         r = sd_bus_new(&b);
1425         if (r < 0)
1426                 return r;
1427
1428         r = bus_set_address_system_remote(b, host);
1429         if (r < 0)
1430                 return r;
1431
1432         b->bus_client = true;
1433         b->trusted = false;
1434         b->is_system = true;
1435         b->is_local = false;
1436
1437         r = sd_bus_start(b);
1438         if (r < 0)
1439                 return r;
1440
1441         *ret = TAKE_PTR(b);
1442         return 0;
1443 }
1444
1445 int bus_set_address_system_machine(sd_bus *b, const char *machine) {
1446         _cleanup_free_ char *e = NULL;
1447         char *a;
1448
1449         assert(b);
1450         assert(machine);
1451
1452         e = bus_address_escape(machine);
1453         if (!e)
1454                 return -ENOMEM;
1455
1456         a = strjoin("x-machine-unix:machine=", e);
1457         if (!a)
1458                 return -ENOMEM;
1459
1460         return free_and_replace(b->address, a);
1461 }
1462
1463 _public_ int sd_bus_open_system_machine(sd_bus **ret, const char *machine) {
1464         _cleanup_(bus_freep) sd_bus *b = NULL;
1465         int r;
1466
1467         assert_return(machine, -EINVAL);
1468         assert_return(ret, -EINVAL);
1469         assert_return(machine_name_is_valid(machine), -EINVAL);
1470
1471         r = sd_bus_new(&b);
1472         if (r < 0)
1473                 return r;
1474
1475         r = bus_set_address_system_machine(b, machine);
1476         if (r < 0)
1477                 return r;
1478
1479         b->bus_client = true;
1480         b->trusted = false;
1481         b->is_system = true;
1482         b->is_local = false;
1483
1484         r = sd_bus_start(b);
1485         if (r < 0)
1486                 return r;
1487
1488         *ret = TAKE_PTR(b);
1489         return 0;
1490 }
1491
1492 _public_ void sd_bus_close(sd_bus *bus) {
1493         if (!bus)
1494                 return;
1495         if (bus->state == BUS_CLOSED)
1496                 return;
1497         if (bus_pid_changed(bus))
1498                 return;
1499
1500         /* Don't leave ssh hanging around */
1501         bus_kill_exec(bus);
1502
1503         bus_set_state(bus, BUS_CLOSED);
1504
1505         sd_bus_detach_event(bus);
1506
1507         /* Drop all queued messages so that they drop references to
1508          * the bus object and the bus may be freed */
1509         bus_reset_queues(bus);
1510
1511         bus_close_io_fds(bus);
1512         bus_close_inotify_fd(bus);
1513 }
1514
1515 _public_ sd_bus* sd_bus_flush_close_unref(sd_bus *bus) {
1516         if (!bus)
1517                 return NULL;
1518
1519         /* Have to do this before flush() to prevent hang */
1520         bus_kill_exec(bus);
1521
1522         sd_bus_flush(bus);
1523         sd_bus_close(bus);
1524
1525         return sd_bus_unref(bus);
1526 }
1527
1528 void bus_enter_closing(sd_bus *bus) {
1529         assert(bus);
1530
1531         if (!IN_SET(bus->state, BUS_WATCH_BIND, BUS_OPENING, BUS_AUTHENTICATING, BUS_HELLO, BUS_RUNNING))
1532                 return;
1533
1534         bus_set_state(bus, BUS_CLOSING);
1535 }
1536
1537 _public_ sd_bus *sd_bus_ref(sd_bus *bus) {
1538         if (!bus)
1539                 return NULL;
1540
1541         assert_se(REFCNT_INC(bus->n_ref) >= 2);
1542
1543         return bus;
1544 }
1545
1546 _public_ sd_bus *sd_bus_unref(sd_bus *bus) {
1547         unsigned i;
1548
1549         if (!bus)
1550                 return NULL;
1551
1552         i = REFCNT_DEC(bus->n_ref);
1553         if (i > 0)
1554                 return NULL;
1555
1556         return bus_free(bus);
1557 }
1558
1559 _public_ int sd_bus_is_open(sd_bus *bus) {
1560         assert_return(bus, -EINVAL);
1561         assert_return(bus = bus_resolve(bus), -ENOPKG);
1562         assert_return(!bus_pid_changed(bus), -ECHILD);
1563
1564         return BUS_IS_OPEN(bus->state);
1565 }
1566
1567 _public_ int sd_bus_is_ready(sd_bus *bus) {
1568         assert_return(bus, -EINVAL);
1569         assert_return(bus = bus_resolve(bus), -ENOPKG);
1570         assert_return(!bus_pid_changed(bus), -ECHILD);
1571
1572         return bus->state == BUS_RUNNING;
1573 }
1574
1575 _public_ int sd_bus_can_send(sd_bus *bus, char type) {
1576         int r;
1577
1578         assert_return(bus, -EINVAL);
1579         assert_return(bus = bus_resolve(bus), -ENOPKG);
1580         assert_return(bus->state != BUS_UNSET, -ENOTCONN);
1581         assert_return(!bus_pid_changed(bus), -ECHILD);
1582
1583         if (bus->is_monitor)
1584                 return 0;
1585
1586         if (type == SD_BUS_TYPE_UNIX_FD) {
1587                 if (!bus->accept_fd)
1588                         return 0;
1589
1590                 r = bus_ensure_running(bus);
1591                 if (r < 0)
1592                         return r;
1593
1594                 return bus->can_fds;
1595         }
1596
1597         return bus_type_is_valid(type);
1598 }
1599
1600 _public_ int sd_bus_get_bus_id(sd_bus *bus, sd_id128_t *id) {
1601         int r;
1602
1603         assert_return(bus, -EINVAL);
1604         assert_return(bus = bus_resolve(bus), -ENOPKG);
1605         assert_return(id, -EINVAL);
1606         assert_return(!bus_pid_changed(bus), -ECHILD);
1607
1608         r = bus_ensure_running(bus);
1609         if (r < 0)
1610                 return r;
1611
1612         *id = bus->server_id;
1613         return 0;
1614 }
1615
1616 static int bus_seal_message(sd_bus *b, sd_bus_message *m, usec_t timeout) {
1617         int r;
1618
1619         assert(b);
1620         assert(m);
1621
1622         if (m->sealed) {
1623                 /* If we copy the same message to multiple
1624                  * destinations, avoid using the same cookie
1625                  * numbers. */
1626                 b->cookie = MAX(b->cookie, BUS_MESSAGE_COOKIE(m));
1627                 return 0;
1628         }
1629
1630         if (timeout == 0)
1631                 timeout = BUS_DEFAULT_TIMEOUT;
1632
1633         if (!m->sender && b->patch_sender) {
1634                 r = sd_bus_message_set_sender(m, b->patch_sender);
1635                 if (r < 0)
1636                         return r;
1637         }
1638
1639         return sd_bus_message_seal(m, ++b->cookie, timeout);
1640 }
1641
1642 static int bus_remarshal_message(sd_bus *b, sd_bus_message **m) {
1643         bool remarshal = false;
1644
1645         assert(b);
1646
1647         /* wrong packet version */
1648         if (b->message_version != 0 && b->message_version != (*m)->header->version)
1649                 remarshal = true;
1650
1651         /* wrong packet endianness */
1652         if (b->message_endian != 0 && b->message_endian != (*m)->header->endian)
1653                 remarshal = true;
1654
1655         return remarshal ? bus_message_remarshal(b, m) : 0;
1656 }
1657
1658 int bus_seal_synthetic_message(sd_bus *b, sd_bus_message *m) {
1659         assert(b);
1660         assert(m);
1661
1662         /* Fake some timestamps, if they were requested, and not
1663          * already initialized */
1664         if (b->attach_timestamp) {
1665                 if (m->realtime <= 0)
1666                         m->realtime = now(CLOCK_REALTIME);
1667
1668                 if (m->monotonic <= 0)
1669                         m->monotonic = now(CLOCK_MONOTONIC);
1670         }
1671
1672         /* The bus specification says the serial number cannot be 0,
1673          * hence let's fill something in for synthetic messages. Since
1674          * synthetic messages might have a fake sender and we don't
1675          * want to interfere with the real sender's serial numbers we
1676          * pick a fixed, artificial one. We use (uint32_t) -1 rather
1677          * than (uint64_t) -1 since dbus1 only had 32bit identifiers,
1678          * even though kdbus can do 64bit. */
1679         return sd_bus_message_seal(m, 0xFFFFFFFFULL, 0);
1680 }
1681
1682 static int bus_write_message(sd_bus *bus, sd_bus_message *m, size_t *idx) {
1683         int r;
1684
1685         assert(bus);
1686         assert(m);
1687
1688         r = bus_socket_write_message(bus, m, idx);
1689         if (r <= 0)
1690                 return r;
1691
1692         if (*idx >= BUS_MESSAGE_SIZE(m))
1693                 log_debug("Sent message type=%s sender=%s destination=%s path=%s interface=%s member=%s cookie=%" PRIu64 " reply_cookie=%" PRIu64 " signature=%s error-name=%s error-message=%s",
1694                           bus_message_type_to_string(m->header->type),
1695                           strna(sd_bus_message_get_sender(m)),
1696                           strna(sd_bus_message_get_destination(m)),
1697                           strna(sd_bus_message_get_path(m)),
1698                           strna(sd_bus_message_get_interface(m)),
1699                           strna(sd_bus_message_get_member(m)),
1700                           BUS_MESSAGE_COOKIE(m),
1701                           m->reply_cookie,
1702                           strna(m->root_container.signature),
1703                           strna(m->error.name),
1704                           strna(m->error.message));
1705
1706         return r;
1707 }
1708
1709 static int dispatch_wqueue(sd_bus *bus) {
1710         int r, ret = 0;
1711
1712         assert(bus);
1713         assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1714
1715         while (bus->wqueue_size > 0) {
1716
1717                 r = bus_write_message(bus, bus->wqueue[0], &bus->windex);
1718                 if (r < 0)
1719                         return r;
1720                 else if (r == 0)
1721                         /* Didn't do anything this time */
1722                         return ret;
1723                 else if (bus->windex >= BUS_MESSAGE_SIZE(bus->wqueue[0])) {
1724                         /* Fully written. Let's drop the entry from
1725                          * the queue.
1726                          *
1727                          * This isn't particularly optimized, but
1728                          * well, this is supposed to be our worst-case
1729                          * buffer only, and the socket buffer is
1730                          * supposed to be our primary buffer, and if
1731                          * it got full, then all bets are off
1732                          * anyway. */
1733
1734                         bus->wqueue_size--;
1735                         sd_bus_message_unref(bus->wqueue[0]);
1736                         memmove(bus->wqueue, bus->wqueue + 1, sizeof(sd_bus_message*) * bus->wqueue_size);
1737                         bus->windex = 0;
1738
1739                         ret = 1;
1740                 }
1741         }
1742
1743         return ret;
1744 }
1745
1746 static int bus_read_message(sd_bus *bus, bool hint_priority, int64_t priority) {
1747         assert(bus);
1748
1749         return bus_socket_read_message(bus);
1750 }
1751
1752 int bus_rqueue_make_room(sd_bus *bus) {
1753         assert(bus);
1754
1755         if (bus->rqueue_size >= BUS_RQUEUE_MAX)
1756                 return -ENOBUFS;
1757
1758         if (!GREEDY_REALLOC(bus->rqueue, bus->rqueue_allocated, bus->rqueue_size + 1))
1759                 return -ENOMEM;
1760
1761         return 0;
1762 }
1763
1764 static int dispatch_rqueue(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **m) {
1765         int r, ret = 0;
1766
1767         assert(bus);
1768         assert(m);
1769         assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
1770
1771         /* Note that the priority logic is only available on kdbus,
1772          * where the rqueue is unused. We check the rqueue here
1773          * anyway, because it's simple... */
1774
1775         for (;;) {
1776                 if (bus->rqueue_size > 0) {
1777                         /* Dispatch a queued message */
1778
1779                         *m = bus->rqueue[0];
1780                         bus->rqueue_size--;
1781                         memmove(bus->rqueue, bus->rqueue + 1, sizeof(sd_bus_message*) * bus->rqueue_size);
1782                         return 1;
1783                 }
1784
1785                 /* Try to read a new message */
1786                 r = bus_read_message(bus, hint_priority, priority);
1787                 if (r < 0)
1788                         return r;
1789                 if (r == 0)
1790                         return ret;
1791
1792                 ret = 1;
1793         }
1794 }
1795
1796 _public_ int sd_bus_send(sd_bus *bus, sd_bus_message *_m, uint64_t *cookie) {
1797         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = sd_bus_message_ref(_m);
1798         int r;
1799
1800         assert_return(m, -EINVAL);
1801
1802         if (!bus)
1803                 bus = m->bus;
1804
1805         assert_return(!bus_pid_changed(bus), -ECHILD);
1806
1807         if (!BUS_IS_OPEN(bus->state))
1808                 return -ENOTCONN;
1809
1810         if (m->n_fds > 0) {
1811                 r = sd_bus_can_send(bus, SD_BUS_TYPE_UNIX_FD);
1812                 if (r < 0)
1813                         return r;
1814                 if (r == 0)
1815                         return -EOPNOTSUPP;
1816         }
1817
1818         /* If the cookie number isn't kept, then we know that no reply
1819          * is expected */
1820         if (!cookie && !m->sealed)
1821                 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1822
1823         r = bus_seal_message(bus, m, 0);
1824         if (r < 0)
1825                 return r;
1826
1827         /* Remarshall if we have to. This will possibly unref the
1828          * message and place a replacement in m */
1829         r = bus_remarshal_message(bus, &m);
1830         if (r < 0)
1831                 return r;
1832
1833         /* If this is a reply and no reply was requested, then let's
1834          * suppress this, if we can */
1835         if (m->dont_send)
1836                 goto finish;
1837
1838         if (IN_SET(bus->state, BUS_RUNNING, BUS_HELLO) && bus->wqueue_size <= 0) {
1839                 size_t idx = 0;
1840
1841                 r = bus_write_message(bus, m, &idx);
1842                 if (r < 0) {
1843                         if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
1844                                 bus_enter_closing(bus);
1845                                 return -ECONNRESET;
1846                         }
1847
1848                         return r;
1849                 }
1850
1851                 if (idx < BUS_MESSAGE_SIZE(m))  {
1852                         /* Wasn't fully written. So let's remember how
1853                          * much was written. Note that the first entry
1854                          * of the wqueue array is always allocated so
1855                          * that we always can remember how much was
1856                          * written. */
1857                         bus->wqueue[0] = sd_bus_message_ref(m);
1858                         bus->wqueue_size = 1;
1859                         bus->windex = idx;
1860                 }
1861
1862         } else {
1863                 /* Just append it to the queue. */
1864
1865                 if (bus->wqueue_size >= BUS_WQUEUE_MAX)
1866                         return -ENOBUFS;
1867
1868                 if (!GREEDY_REALLOC(bus->wqueue, bus->wqueue_allocated, bus->wqueue_size + 1))
1869                         return -ENOMEM;
1870
1871                 bus->wqueue[bus->wqueue_size++] = sd_bus_message_ref(m);
1872         }
1873
1874 finish:
1875         if (cookie)
1876                 *cookie = BUS_MESSAGE_COOKIE(m);
1877
1878         return 1;
1879 }
1880
1881 _public_ int sd_bus_send_to(sd_bus *bus, sd_bus_message *m, const char *destination, uint64_t *cookie) {
1882         int r;
1883
1884         assert_return(m, -EINVAL);
1885
1886         if (!bus)
1887                 bus = m->bus;
1888
1889         assert_return(!bus_pid_changed(bus), -ECHILD);
1890
1891         if (!BUS_IS_OPEN(bus->state))
1892                 return -ENOTCONN;
1893
1894         if (!streq_ptr(m->destination, destination)) {
1895
1896                 if (!destination)
1897                         return -EEXIST;
1898
1899                 r = sd_bus_message_set_destination(m, destination);
1900                 if (r < 0)
1901                         return r;
1902         }
1903
1904         return sd_bus_send(bus, m, cookie);
1905 }
1906
1907 static usec_t calc_elapse(sd_bus *bus, uint64_t usec) {
1908         assert(bus);
1909
1910         if (usec == (uint64_t) -1)
1911                 return 0;
1912
1913         /* We start all timeouts the instant we enter BUS_HELLO/BUS_RUNNING state, so that the don't run in parallel
1914          * with any connection setup states. Hence, if a method callback is started earlier than that we just store the
1915          * relative timestamp, and afterwards the absolute one. */
1916
1917         if (IN_SET(bus->state, BUS_WATCH_BIND, BUS_OPENING, BUS_AUTHENTICATING))
1918                 return usec;
1919         else
1920                 return now(CLOCK_MONOTONIC) + usec;
1921 }
1922
1923 static int timeout_compare(const void *a, const void *b) {
1924         const struct reply_callback *x = a, *y = b;
1925
1926         if (x->timeout_usec != 0 && y->timeout_usec == 0)
1927                 return -1;
1928
1929         if (x->timeout_usec == 0 && y->timeout_usec != 0)
1930                 return 1;
1931
1932         if (x->timeout_usec < y->timeout_usec)
1933                 return -1;
1934
1935         if (x->timeout_usec > y->timeout_usec)
1936                 return 1;
1937
1938         return 0;
1939 }
1940
1941 _public_ int sd_bus_call_async(
1942                 sd_bus *bus,
1943                 sd_bus_slot **slot,
1944                 sd_bus_message *_m,
1945                 sd_bus_message_handler_t callback,
1946                 void *userdata,
1947                 uint64_t usec) {
1948
1949         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = sd_bus_message_ref(_m);
1950         _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *s = NULL;
1951         int r;
1952
1953         assert_return(m, -EINVAL);
1954         assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL);
1955         assert_return(!m->sealed || (!!callback == !(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)), -EINVAL);
1956
1957         if (!bus)
1958                 bus = m->bus;
1959
1960         assert_return(!bus_pid_changed(bus), -ECHILD);
1961
1962         if (!BUS_IS_OPEN(bus->state))
1963                 return -ENOTCONN;
1964
1965         /* If no callback is specified and there's no interest in a slot, then there's no reason to ask for a reply */
1966         if (!callback && !slot && !m->sealed)
1967                 m->header->flags |= BUS_MESSAGE_NO_REPLY_EXPECTED;
1968
1969         r = ordered_hashmap_ensure_allocated(&bus->reply_callbacks, &uint64_hash_ops);
1970         if (r < 0)
1971                 return r;
1972
1973         r = prioq_ensure_allocated(&bus->reply_callbacks_prioq, timeout_compare);
1974         if (r < 0)
1975                 return r;
1976
1977         r = bus_seal_message(bus, m, usec);
1978         if (r < 0)
1979                 return r;
1980
1981         r = bus_remarshal_message(bus, &m);
1982         if (r < 0)
1983                 return r;
1984
1985         if (slot || callback) {
1986                 s = bus_slot_allocate(bus, !slot, BUS_REPLY_CALLBACK, sizeof(struct reply_callback), userdata);
1987                 if (!s)
1988                         return -ENOMEM;
1989
1990                 s->reply_callback.callback = callback;
1991
1992                 s->reply_callback.cookie = BUS_MESSAGE_COOKIE(m);
1993                 r = ordered_hashmap_put(bus->reply_callbacks, &s->reply_callback.cookie, &s->reply_callback);
1994                 if (r < 0) {
1995                         s->reply_callback.cookie = 0;
1996                         return r;
1997                 }
1998
1999                 s->reply_callback.timeout_usec = calc_elapse(bus, m->timeout);
2000                 if (s->reply_callback.timeout_usec != 0) {
2001                         r = prioq_put(bus->reply_callbacks_prioq, &s->reply_callback, &s->reply_callback.prioq_idx);
2002                         if (r < 0) {
2003                                 s->reply_callback.timeout_usec = 0;
2004                                 return r;
2005                         }
2006                 }
2007         }
2008
2009         r = sd_bus_send(bus, m, s ? &s->reply_callback.cookie : NULL);
2010         if (r < 0)
2011                 return r;
2012
2013         if (slot)
2014                 *slot = s;
2015         s = NULL;
2016
2017         return r;
2018 }
2019
2020 int bus_ensure_running(sd_bus *bus) {
2021         int r;
2022
2023         assert(bus);
2024
2025         if (IN_SET(bus->state, BUS_UNSET, BUS_CLOSED, BUS_CLOSING))
2026                 return -ENOTCONN;
2027         if (bus->state == BUS_RUNNING)
2028                 return 1;
2029
2030         for (;;) {
2031                 r = sd_bus_process(bus, NULL);
2032                 if (r < 0)
2033                         return r;
2034                 if (bus->state == BUS_RUNNING)
2035                         return 1;
2036                 if (r > 0)
2037                         continue;
2038
2039                 r = sd_bus_wait(bus, (uint64_t) -1);
2040                 if (r < 0)
2041                         return r;
2042         }
2043 }
2044
2045 _public_ int sd_bus_call(
2046                 sd_bus *bus,
2047                 sd_bus_message *_m,
2048                 uint64_t usec,
2049                 sd_bus_error *error,
2050                 sd_bus_message **reply) {
2051
2052         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = sd_bus_message_ref(_m);
2053         usec_t timeout;
2054         uint64_t cookie;
2055         unsigned i;
2056         int r;
2057
2058         bus_assert_return(m, -EINVAL, error);
2059         bus_assert_return(m->header->type == SD_BUS_MESSAGE_METHOD_CALL, -EINVAL, error);
2060         bus_assert_return(!(m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED), -EINVAL, error);
2061         bus_assert_return(!bus_error_is_dirty(error), -EINVAL, error);
2062
2063         if (!bus)
2064                 bus = m->bus;
2065
2066         bus_assert_return(!bus_pid_changed(bus), -ECHILD, error);
2067
2068         if (!BUS_IS_OPEN(bus->state)) {
2069                 r = -ENOTCONN;
2070                 goto fail;
2071         }
2072
2073         r = bus_ensure_running(bus);
2074         if (r < 0)
2075                 goto fail;
2076
2077         i = bus->rqueue_size;
2078
2079         r = bus_seal_message(bus, m, usec);
2080         if (r < 0)
2081                 goto fail;
2082
2083         r = bus_remarshal_message(bus, &m);
2084         if (r < 0)
2085                 goto fail;
2086
2087         r = sd_bus_send(bus, m, &cookie);
2088         if (r < 0)
2089                 goto fail;
2090
2091         timeout = calc_elapse(bus, m->timeout);
2092
2093         for (;;) {
2094                 usec_t left;
2095
2096                 while (i < bus->rqueue_size) {
2097                         sd_bus_message *incoming = NULL;
2098
2099                         incoming = bus->rqueue[i];
2100
2101                         if (incoming->reply_cookie == cookie) {
2102                                 /* Found a match! */
2103
2104                                 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
2105                                 bus->rqueue_size--;
2106                                 log_debug_bus_message(incoming);
2107
2108                                 if (incoming->header->type == SD_BUS_MESSAGE_METHOD_RETURN) {
2109
2110                                         if (incoming->n_fds <= 0 || bus->accept_fd) {
2111                                                 if (reply)
2112                                                         *reply = incoming;
2113                                                 else
2114                                                         sd_bus_message_unref(incoming);
2115
2116                                                 return 1;
2117                                         }
2118
2119                                         r = sd_bus_error_setf(error, SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Reply message contained file descriptors which I couldn't accept. Sorry.");
2120                                         sd_bus_message_unref(incoming);
2121                                         return r;
2122
2123                                 } else if (incoming->header->type == SD_BUS_MESSAGE_METHOD_ERROR) {
2124                                         r = sd_bus_error_copy(error, &incoming->error);
2125                                         sd_bus_message_unref(incoming);
2126                                         return r;
2127                                 } else {
2128                                         r = -EIO;
2129                                         goto fail;
2130                                 }
2131
2132                         } else if (BUS_MESSAGE_COOKIE(incoming) == cookie &&
2133                                    bus->unique_name &&
2134                                    incoming->sender &&
2135                                    streq(bus->unique_name, incoming->sender)) {
2136
2137                                 memmove(bus->rqueue + i, bus->rqueue + i + 1, sizeof(sd_bus_message*) * (bus->rqueue_size - i - 1));
2138                                 bus->rqueue_size--;
2139
2140                                 /* Our own message? Somebody is trying
2141                                  * to send its own client a message,
2142                                  * let's not dead-lock, let's fail
2143                                  * immediately. */
2144
2145                                 sd_bus_message_unref(incoming);
2146                                 r = -ELOOP;
2147                                 goto fail;
2148                         }
2149
2150                         /* Try to read more, right-away */
2151                         i++;
2152                 }
2153
2154                 r = bus_read_message(bus, false, 0);
2155                 if (r < 0) {
2156                         if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
2157                                 bus_enter_closing(bus);
2158                                 r = -ECONNRESET;
2159                         }
2160
2161                         goto fail;
2162                 }
2163                 if (r > 0)
2164                         continue;
2165
2166                 if (timeout > 0) {
2167                         usec_t n;
2168
2169                         n = now(CLOCK_MONOTONIC);
2170                         if (n >= timeout) {
2171                                 r = -ETIMEDOUT;
2172                                 goto fail;
2173                         }
2174
2175                         left = timeout - n;
2176                 } else
2177                         left = (uint64_t) -1;
2178
2179                 r = bus_poll(bus, true, left);
2180                 if (r < 0)
2181                         goto fail;
2182                 if (r == 0) {
2183                         r = -ETIMEDOUT;
2184                         goto fail;
2185                 }
2186
2187                 r = dispatch_wqueue(bus);
2188                 if (r < 0) {
2189                         if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
2190                                 bus_enter_closing(bus);
2191                                 r = -ECONNRESET;
2192                         }
2193
2194                         goto fail;
2195                 }
2196         }
2197
2198 fail:
2199         return sd_bus_error_set_errno(error, r);
2200 }
2201
2202 _public_ int sd_bus_get_fd(sd_bus *bus) {
2203
2204         assert_return(bus, -EINVAL);
2205         assert_return(bus = bus_resolve(bus), -ENOPKG);
2206         assert_return(bus->input_fd == bus->output_fd, -EPERM);
2207         assert_return(!bus_pid_changed(bus), -ECHILD);
2208
2209         if (bus->state == BUS_CLOSED)
2210                 return -ENOTCONN;
2211
2212         if (bus->inotify_fd >= 0)
2213                 return bus->inotify_fd;
2214
2215         if (bus->input_fd >= 0)
2216                 return bus->input_fd;
2217
2218         return -ENOTCONN;
2219 }
2220
2221 _public_ int sd_bus_get_events(sd_bus *bus) {
2222         int flags = 0;
2223
2224         assert_return(bus, -EINVAL);
2225         assert_return(bus = bus_resolve(bus), -ENOPKG);
2226         assert_return(!bus_pid_changed(bus), -ECHILD);
2227
2228         switch (bus->state) {
2229
2230         case BUS_UNSET:
2231         case BUS_CLOSED:
2232                 return -ENOTCONN;
2233
2234         case BUS_WATCH_BIND:
2235                 flags |= POLLIN;
2236                 break;
2237
2238         case BUS_OPENING:
2239                 flags |= POLLOUT;
2240                 break;
2241
2242         case BUS_AUTHENTICATING:
2243                 if (bus_socket_auth_needs_write(bus))
2244                         flags |= POLLOUT;
2245
2246                 flags |= POLLIN;
2247                 break;
2248
2249         case BUS_RUNNING:
2250         case BUS_HELLO:
2251                 if (bus->rqueue_size <= 0)
2252                         flags |= POLLIN;
2253                 if (bus->wqueue_size > 0)
2254                         flags |= POLLOUT;
2255                 break;
2256
2257         case BUS_CLOSING:
2258                 break;
2259
2260         default:
2261                 assert_not_reached("Unknown state");
2262         }
2263
2264         return flags;
2265 }
2266
2267 _public_ int sd_bus_get_timeout(sd_bus *bus, uint64_t *timeout_usec) {
2268         struct reply_callback *c;
2269
2270         assert_return(bus, -EINVAL);
2271         assert_return(bus = bus_resolve(bus), -ENOPKG);
2272         assert_return(timeout_usec, -EINVAL);
2273         assert_return(!bus_pid_changed(bus), -ECHILD);
2274
2275         if (!BUS_IS_OPEN(bus->state) && bus->state != BUS_CLOSING)
2276                 return -ENOTCONN;
2277
2278         if (bus->track_queue) {
2279                 *timeout_usec = 0;
2280                 return 1;
2281         }
2282
2283         switch (bus->state) {
2284
2285         case BUS_AUTHENTICATING:
2286                 *timeout_usec = bus->auth_timeout;
2287                 return 1;
2288
2289         case BUS_RUNNING:
2290         case BUS_HELLO:
2291                 if (bus->rqueue_size > 0) {
2292                         *timeout_usec = 0;
2293                         return 1;
2294                 }
2295
2296                 c = prioq_peek(bus->reply_callbacks_prioq);
2297                 if (!c) {
2298                         *timeout_usec = (uint64_t) -1;
2299                         return 0;
2300                 }
2301
2302                 if (c->timeout_usec == 0) {
2303                         *timeout_usec = (uint64_t) -1;
2304                         return 0;
2305                 }
2306
2307                 *timeout_usec = c->timeout_usec;
2308                 return 1;
2309
2310         case BUS_CLOSING:
2311                 *timeout_usec = 0;
2312                 return 1;
2313
2314         case BUS_WATCH_BIND:
2315         case BUS_OPENING:
2316                 *timeout_usec = (uint64_t) -1;
2317                 return 0;
2318
2319         default:
2320                 assert_not_reached("Unknown or unexpected stat");
2321         }
2322 }
2323
2324 static int process_timeout(sd_bus *bus) {
2325         _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2326         _cleanup_(sd_bus_message_unrefp) sd_bus_message* m = NULL;
2327         struct reply_callback *c;
2328         sd_bus_slot *slot;
2329         bool is_hello;
2330         usec_t n;
2331         int r;
2332
2333         assert(bus);
2334         assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
2335
2336         c = prioq_peek(bus->reply_callbacks_prioq);
2337         if (!c)
2338                 return 0;
2339
2340         n = now(CLOCK_MONOTONIC);
2341         if (c->timeout_usec > n)
2342                 return 0;
2343
2344         r = bus_message_new_synthetic_error(
2345                         bus,
2346                         c->cookie,
2347                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Method call timed out"),
2348                         &m);
2349         if (r < 0)
2350                 return r;
2351
2352         r = bus_seal_synthetic_message(bus, m);
2353         if (r < 0)
2354                 return r;
2355
2356         assert_se(prioq_pop(bus->reply_callbacks_prioq) == c);
2357         c->timeout_usec = 0;
2358
2359         ordered_hashmap_remove(bus->reply_callbacks, &c->cookie);
2360         c->cookie = 0;
2361
2362         slot = container_of(c, sd_bus_slot, reply_callback);
2363
2364         bus->iteration_counter++;
2365
2366         is_hello = bus->state == BUS_HELLO && c->callback == hello_callback;
2367
2368         bus->current_message = m;
2369         bus->current_slot = sd_bus_slot_ref(slot);
2370         bus->current_handler = c->callback;
2371         bus->current_userdata = slot->userdata;
2372         r = c->callback(m, slot->userdata, &error_buffer);
2373         bus->current_userdata = NULL;
2374         bus->current_handler = NULL;
2375         bus->current_slot = NULL;
2376         bus->current_message = NULL;
2377
2378         if (slot->floating) {
2379                 bus_slot_disconnect(slot);
2380                 sd_bus_slot_unref(slot);
2381         }
2382
2383         sd_bus_slot_unref(slot);
2384
2385         /* When this is the hello message and it timed out, then make sure to propagate the error up, don't just log
2386          * and ignore the callback handler's return value. */
2387         if (is_hello)
2388                 return r;
2389
2390         return bus_maybe_reply_error(m, r, &error_buffer);
2391 }
2392
2393 static int process_hello(sd_bus *bus, sd_bus_message *m) {
2394         assert(bus);
2395         assert(m);
2396
2397         if (bus->state != BUS_HELLO)
2398                 return 0;
2399
2400         /* Let's make sure the first message on the bus is the HELLO
2401          * reply. But note that we don't actually parse the message
2402          * here (we leave that to the usual handling), we just verify
2403          * we don't let any earlier msg through. */
2404
2405         if (!IN_SET(m->header->type, SD_BUS_MESSAGE_METHOD_RETURN, SD_BUS_MESSAGE_METHOD_ERROR))
2406                 return -EIO;
2407
2408         if (m->reply_cookie != 1)
2409                 return -EIO;
2410
2411         return 0;
2412 }
2413
2414 static int process_reply(sd_bus *bus, sd_bus_message *m) {
2415         _cleanup_(sd_bus_message_unrefp) sd_bus_message *synthetic_reply = NULL;
2416         _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2417         struct reply_callback *c;
2418         sd_bus_slot *slot;
2419         bool is_hello;
2420         int r;
2421
2422         assert(bus);
2423         assert(m);
2424
2425         if (!IN_SET(m->header->type, SD_BUS_MESSAGE_METHOD_RETURN, SD_BUS_MESSAGE_METHOD_ERROR))
2426                 return 0;
2427
2428         if (m->destination && bus->unique_name && !streq_ptr(m->destination, bus->unique_name))
2429                 return 0;
2430
2431         c = ordered_hashmap_remove(bus->reply_callbacks, &m->reply_cookie);
2432         if (!c)
2433                 return 0;
2434
2435         c->cookie = 0;
2436
2437         slot = container_of(c, sd_bus_slot, reply_callback);
2438
2439         if (m->n_fds > 0 && !bus->accept_fd) {
2440
2441                 /* If the reply contained a file descriptor which we
2442                  * didn't want we pass an error instead. */
2443
2444                 r = bus_message_new_synthetic_error(
2445                                 bus,
2446                                 m->reply_cookie,
2447                                 &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Reply message contained file descriptor"),
2448                                 &synthetic_reply);
2449                 if (r < 0)
2450                         return r;
2451
2452                 /* Copy over original timestamp */
2453                 synthetic_reply->realtime = m->realtime;
2454                 synthetic_reply->monotonic = m->monotonic;
2455                 synthetic_reply->seqnum = m->seqnum;
2456
2457                 r = bus_seal_synthetic_message(bus, synthetic_reply);
2458                 if (r < 0)
2459                         return r;
2460
2461                 m = synthetic_reply;
2462         } else {
2463                 r = sd_bus_message_rewind(m, true);
2464                 if (r < 0)
2465                         return r;
2466         }
2467
2468         if (c->timeout_usec != 0) {
2469                 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2470                 c->timeout_usec = 0;
2471         }
2472
2473         is_hello = bus->state == BUS_HELLO && c->callback == hello_callback;
2474
2475         bus->current_slot = sd_bus_slot_ref(slot);
2476         bus->current_handler = c->callback;
2477         bus->current_userdata = slot->userdata;
2478         r = c->callback(m, slot->userdata, &error_buffer);
2479         bus->current_userdata = NULL;
2480         bus->current_handler = NULL;
2481         bus->current_slot = NULL;
2482
2483         if (slot->floating) {
2484                 bus_slot_disconnect(slot);
2485                 sd_bus_slot_unref(slot);
2486         }
2487
2488         sd_bus_slot_unref(slot);
2489
2490         /* When this is the hello message and it failed, then make sure to propagate the error up, don't just log and
2491          * ignore the callback handler's return value. */
2492         if (is_hello)
2493                 return r;
2494
2495         return bus_maybe_reply_error(m, r, &error_buffer);
2496 }
2497
2498 static int process_filter(sd_bus *bus, sd_bus_message *m) {
2499         _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2500         struct filter_callback *l;
2501         int r;
2502
2503         assert(bus);
2504         assert(m);
2505
2506         do {
2507                 bus->filter_callbacks_modified = false;
2508
2509                 LIST_FOREACH(callbacks, l, bus->filter_callbacks) {
2510                         sd_bus_slot *slot;
2511
2512                         if (bus->filter_callbacks_modified)
2513                                 break;
2514
2515                         /* Don't run this more than once per iteration */
2516                         if (l->last_iteration == bus->iteration_counter)
2517                                 continue;
2518
2519                         l->last_iteration = bus->iteration_counter;
2520
2521                         r = sd_bus_message_rewind(m, true);
2522                         if (r < 0)
2523                                 return r;
2524
2525                         slot = container_of(l, sd_bus_slot, filter_callback);
2526
2527                         bus->current_slot = sd_bus_slot_ref(slot);
2528                         bus->current_handler = l->callback;
2529                         bus->current_userdata = slot->userdata;
2530                         r = l->callback(m, slot->userdata, &error_buffer);
2531                         bus->current_userdata = NULL;
2532                         bus->current_handler = NULL;
2533                         bus->current_slot = sd_bus_slot_unref(slot);
2534
2535                         r = bus_maybe_reply_error(m, r, &error_buffer);
2536                         if (r != 0)
2537                                 return r;
2538
2539                 }
2540
2541         } while (bus->filter_callbacks_modified);
2542
2543         return 0;
2544 }
2545
2546 static int process_match(sd_bus *bus, sd_bus_message *m) {
2547         int r;
2548
2549         assert(bus);
2550         assert(m);
2551
2552         do {
2553                 bus->match_callbacks_modified = false;
2554
2555                 r = bus_match_run(bus, &bus->match_callbacks, m);
2556                 if (r != 0)
2557                         return r;
2558
2559         } while (bus->match_callbacks_modified);
2560
2561         return 0;
2562 }
2563
2564 static int process_builtin(sd_bus *bus, sd_bus_message *m) {
2565         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2566         int r;
2567
2568         assert(bus);
2569         assert(m);
2570
2571         if (bus->is_monitor)
2572                 return 0;
2573
2574         if (bus->manual_peer_interface)
2575                 return 0;
2576
2577         if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2578                 return 0;
2579
2580         if (!streq_ptr(m->interface, "org.freedesktop.DBus.Peer"))
2581                 return 0;
2582
2583         if (m->header->flags & BUS_MESSAGE_NO_REPLY_EXPECTED)
2584                 return 1;
2585
2586         if (streq_ptr(m->member, "Ping"))
2587                 r = sd_bus_message_new_method_return(m, &reply);
2588         else if (streq_ptr(m->member, "GetMachineId")) {
2589                 sd_id128_t id;
2590                 char sid[33];
2591
2592                 r = sd_id128_get_machine(&id);
2593                 if (r < 0)
2594                         return r;
2595
2596                 r = sd_bus_message_new_method_return(m, &reply);
2597                 if (r < 0)
2598                         return r;
2599
2600                 r = sd_bus_message_append(reply, "s", sd_id128_to_string(id, sid));
2601         } else {
2602                 r = sd_bus_message_new_method_errorf(
2603                                 m, &reply,
2604                                 SD_BUS_ERROR_UNKNOWN_METHOD,
2605                                  "Unknown method '%s' on interface '%s'.", m->member, m->interface);
2606         }
2607
2608         if (r < 0)
2609                 return r;
2610
2611         r = sd_bus_send(bus, reply, NULL);
2612         if (r < 0)
2613                 return r;
2614
2615         return 1;
2616 }
2617
2618 static int process_fd_check(sd_bus *bus, sd_bus_message *m) {
2619         assert(bus);
2620         assert(m);
2621
2622         /* If we got a message with a file descriptor which we didn't
2623          * want to accept, then let's drop it. How can this even
2624          * happen? For example, when the kernel queues a message into
2625          * an activatable names's queue which allows fds, and then is
2626          * delivered to us later even though we ourselves did not
2627          * negotiate it. */
2628
2629         if (bus->is_monitor)
2630                 return 0;
2631
2632         if (m->n_fds <= 0)
2633                 return 0;
2634
2635         if (bus->accept_fd)
2636                 return 0;
2637
2638         if (m->header->type != SD_BUS_MESSAGE_METHOD_CALL)
2639                 return 1; /* just eat it up */
2640
2641         return sd_bus_reply_method_errorf(m, SD_BUS_ERROR_INCONSISTENT_MESSAGE, "Message contains file descriptors, which I cannot accept. Sorry.");
2642 }
2643
2644 static int process_message(sd_bus *bus, sd_bus_message *m) {
2645         int r;
2646
2647         assert(bus);
2648         assert(m);
2649
2650         bus->current_message = m;
2651         bus->iteration_counter++;
2652
2653         log_debug_bus_message(m);
2654
2655         r = process_hello(bus, m);
2656         if (r != 0)
2657                 goto finish;
2658
2659         r = process_reply(bus, m);
2660         if (r != 0)
2661                 goto finish;
2662
2663         r = process_fd_check(bus, m);
2664         if (r != 0)
2665                 goto finish;
2666
2667         r = process_filter(bus, m);
2668         if (r != 0)
2669                 goto finish;
2670
2671         r = process_match(bus, m);
2672         if (r != 0)
2673                 goto finish;
2674
2675         r = process_builtin(bus, m);
2676         if (r != 0)
2677                 goto finish;
2678
2679         r = bus_process_object(bus, m);
2680
2681 finish:
2682         bus->current_message = NULL;
2683         return r;
2684 }
2685
2686 static int dispatch_track(sd_bus *bus) {
2687         assert(bus);
2688
2689         if (!bus->track_queue)
2690                 return 0;
2691
2692         bus_track_dispatch(bus->track_queue);
2693         return 1;
2694 }
2695
2696 static int process_running(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2697         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2698         int r;
2699
2700         assert(bus);
2701         assert(IN_SET(bus->state, BUS_RUNNING, BUS_HELLO));
2702
2703         r = process_timeout(bus);
2704         if (r != 0)
2705                 goto null_message;
2706
2707         r = dispatch_wqueue(bus);
2708         if (r != 0)
2709                 goto null_message;
2710
2711         r = dispatch_track(bus);
2712         if (r != 0)
2713                 goto null_message;
2714
2715         r = dispatch_rqueue(bus, hint_priority, priority, &m);
2716         if (r < 0)
2717                 return r;
2718         if (!m)
2719                 goto null_message;
2720
2721         r = process_message(bus, m);
2722         if (r != 0)
2723                 goto null_message;
2724
2725         if (ret) {
2726                 r = sd_bus_message_rewind(m, true);
2727                 if (r < 0)
2728                         return r;
2729
2730                 *ret = TAKE_PTR(m);
2731
2732                 return 1;
2733         }
2734
2735         if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL) {
2736
2737                 log_debug("Unprocessed message call sender=%s object=%s interface=%s member=%s",
2738                           strna(sd_bus_message_get_sender(m)),
2739                           strna(sd_bus_message_get_path(m)),
2740                           strna(sd_bus_message_get_interface(m)),
2741                           strna(sd_bus_message_get_member(m)));
2742
2743                 r = sd_bus_reply_method_errorf(
2744                                 m,
2745                                 SD_BUS_ERROR_UNKNOWN_OBJECT,
2746                                 "Unknown object '%s'.", m->path);
2747                 if (r < 0)
2748                         return r;
2749         }
2750
2751         return 1;
2752
2753 null_message:
2754         if (r >= 0 && ret)
2755                 *ret = NULL;
2756
2757         return r;
2758 }
2759
2760 static int bus_exit_now(sd_bus *bus) {
2761         assert(bus);
2762
2763         /* Exit due to close, if this is requested. If this is bus object is attached to an event source, invokes
2764          * sd_event_exit(), otherwise invokes libc exit(). */
2765
2766         if (bus->exited) /* did we already exit? */
2767                 return 0;
2768         if (!bus->exit_triggered) /* was the exit condition triggered? */
2769                 return 0;
2770         if (!bus->exit_on_disconnect) /* Shall we actually exit on disconnection? */
2771                 return 0;
2772
2773         bus->exited = true; /* never exit more than once */
2774
2775         log_debug("Bus connection disconnected, exiting.");
2776
2777         if (bus->event)
2778                 return sd_event_exit(bus->event, EXIT_FAILURE);
2779         else
2780                 exit(EXIT_FAILURE);
2781
2782         assert_not_reached("exit() didn't exit?");
2783 }
2784
2785 static int process_closing_reply_callback(sd_bus *bus, struct reply_callback *c) {
2786         _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
2787         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2788         sd_bus_slot *slot;
2789         int r;
2790
2791         assert(bus);
2792         assert(c);
2793
2794         r = bus_message_new_synthetic_error(
2795                         bus,
2796                         c->cookie,
2797                         &SD_BUS_ERROR_MAKE_CONST(SD_BUS_ERROR_NO_REPLY, "Connection terminated"),
2798                         &m);
2799         if (r < 0)
2800                 return r;
2801
2802         r = bus_seal_synthetic_message(bus, m);
2803         if (r < 0)
2804                 return r;
2805
2806         if (c->timeout_usec != 0) {
2807                 prioq_remove(bus->reply_callbacks_prioq, c, &c->prioq_idx);
2808                 c->timeout_usec = 0;
2809         }
2810
2811         ordered_hashmap_remove(bus->reply_callbacks, &c->cookie);
2812         c->cookie = 0;
2813
2814         slot = container_of(c, sd_bus_slot, reply_callback);
2815
2816         bus->iteration_counter++;
2817
2818         bus->current_message = m;
2819         bus->current_slot = sd_bus_slot_ref(slot);
2820         bus->current_handler = c->callback;
2821         bus->current_userdata = slot->userdata;
2822         r = c->callback(m, slot->userdata, &error_buffer);
2823         bus->current_userdata = NULL;
2824         bus->current_handler = NULL;
2825         bus->current_slot = NULL;
2826         bus->current_message = NULL;
2827
2828         if (slot->floating) {
2829                 bus_slot_disconnect(slot);
2830                 sd_bus_slot_unref(slot);
2831         }
2832
2833         sd_bus_slot_unref(slot);
2834
2835         return bus_maybe_reply_error(m, r, &error_buffer);
2836 }
2837
2838 static int process_closing(sd_bus *bus, sd_bus_message **ret) {
2839         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2840         struct reply_callback *c;
2841         int r;
2842
2843         assert(bus);
2844         assert(bus->state == BUS_CLOSING);
2845
2846         /* First, fail all outstanding method calls */
2847         c = ordered_hashmap_first(bus->reply_callbacks);
2848         if (c)
2849                 return process_closing_reply_callback(bus, c);
2850
2851         /* Then, fake-drop all remaining bus tracking references */
2852         if (bus->tracks) {
2853                 bus_track_close(bus->tracks);
2854                 return 1;
2855         }
2856
2857         /* Then, synthesize a Disconnected message */
2858         r = sd_bus_message_new_signal(
2859                         bus,
2860                         &m,
2861                         "/org/freedesktop/DBus/Local",
2862                         "org.freedesktop.DBus.Local",
2863                         "Disconnected");
2864         if (r < 0)
2865                 return r;
2866
2867         bus_message_set_sender_local(bus, m);
2868
2869         r = bus_seal_synthetic_message(bus, m);
2870         if (r < 0)
2871                 return r;
2872
2873         sd_bus_close(bus);
2874
2875         bus->current_message = m;
2876         bus->iteration_counter++;
2877
2878         r = process_filter(bus, m);
2879         if (r != 0)
2880                 goto finish;
2881
2882         r = process_match(bus, m);
2883         if (r != 0)
2884                 goto finish;
2885
2886         /* Nothing else to do, exit now, if the condition holds */
2887         bus->exit_triggered = true;
2888         (void) bus_exit_now(bus);
2889
2890         if (ret)
2891                 *ret = TAKE_PTR(m);
2892
2893         r = 1;
2894
2895 finish:
2896         bus->current_message = NULL;
2897
2898         return r;
2899 }
2900
2901 static int bus_process_internal(sd_bus *bus, bool hint_priority, int64_t priority, sd_bus_message **ret) {
2902         BUS_DONT_DESTROY(bus);
2903         int r;
2904
2905         /* Returns 0 when we didn't do anything. This should cause the
2906          * caller to invoke sd_bus_wait() before returning the next
2907          * time. Returns > 0 when we did something, which possibly
2908          * means *ret is filled in with an unprocessed message. */
2909
2910         assert_return(bus, -EINVAL);
2911         assert_return(bus = bus_resolve(bus), -ENOPKG);
2912         assert_return(!bus_pid_changed(bus), -ECHILD);
2913
2914         /* We don't allow recursively invoking sd_bus_process(). */
2915         assert_return(!bus->current_message, -EBUSY);
2916         assert(!bus->current_slot);
2917
2918         switch (bus->state) {
2919
2920         case BUS_UNSET:
2921                 return -ENOTCONN;
2922
2923         case BUS_CLOSED:
2924                 return -ECONNRESET;
2925
2926         case BUS_WATCH_BIND:
2927                 r = bus_socket_process_watch_bind(bus);
2928                 break;
2929
2930         case BUS_OPENING:
2931                 r = bus_socket_process_opening(bus);
2932                 break;
2933
2934         case BUS_AUTHENTICATING:
2935                 r = bus_socket_process_authenticating(bus);
2936                 break;
2937
2938         case BUS_RUNNING:
2939         case BUS_HELLO:
2940                 r = process_running(bus, hint_priority, priority, ret);
2941                 if (r >= 0)
2942                         return r;
2943
2944                 /* This branch initializes *ret, hence we don't use the generic error checking below */
2945                 break;
2946
2947         case BUS_CLOSING:
2948                 return process_closing(bus, ret);
2949
2950         default:
2951                 assert_not_reached("Unknown state");
2952         }
2953
2954         if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
2955                 bus_enter_closing(bus);
2956                 r = 1;
2957         } else if (r < 0)
2958                 return r;
2959
2960         if (ret)
2961                 *ret = NULL;
2962
2963         return r;
2964 }
2965
2966 _public_ int sd_bus_process(sd_bus *bus, sd_bus_message **ret) {
2967         return bus_process_internal(bus, false, 0, ret);
2968 }
2969
2970 _public_ int sd_bus_process_priority(sd_bus *bus, int64_t priority, sd_bus_message **ret) {
2971         return bus_process_internal(bus, true, priority, ret);
2972 }
2973
2974 static int bus_poll(sd_bus *bus, bool need_more, uint64_t timeout_usec) {
2975         struct pollfd p[2] = {};
2976         int r, n;
2977         struct timespec ts;
2978         usec_t m = USEC_INFINITY;
2979
2980         assert(bus);
2981
2982         if (bus->state == BUS_CLOSING)
2983                 return 1;
2984
2985         if (!BUS_IS_OPEN(bus->state))
2986                 return -ENOTCONN;
2987
2988         if (bus->state == BUS_WATCH_BIND) {
2989                 assert(bus->inotify_fd >= 0);
2990
2991                 p[0].events = POLLIN;
2992                 p[0].fd = bus->inotify_fd;
2993                 n = 1;
2994         } else {
2995                 int e;
2996
2997                 e = sd_bus_get_events(bus);
2998                 if (e < 0)
2999                         return e;
3000
3001                 if (need_more)
3002                         /* The caller really needs some more data, he doesn't
3003                          * care about what's already read, or any timeouts
3004                          * except its own. */
3005                         e |= POLLIN;
3006                 else {
3007                         usec_t until;
3008                         /* The caller wants to process if there's something to
3009                          * process, but doesn't care otherwise */
3010
3011                         r = sd_bus_get_timeout(bus, &until);
3012                         if (r < 0)
3013                                 return r;
3014                         if (r > 0)
3015                                 m = usec_sub_unsigned(until, now(CLOCK_MONOTONIC));
3016                 }
3017
3018                 p[0].fd = bus->input_fd;
3019                 if (bus->output_fd == bus->input_fd) {
3020                         p[0].events = e;
3021                         n = 1;
3022                 } else {
3023                         p[0].events = e & POLLIN;
3024                         p[1].fd = bus->output_fd;
3025                         p[1].events = e & POLLOUT;
3026                         n = 2;
3027                 }
3028         }
3029
3030         if (timeout_usec != (uint64_t) -1 && (m == USEC_INFINITY || timeout_usec < m))
3031                 m = timeout_usec;
3032
3033         r = ppoll(p, n, m == USEC_INFINITY ? NULL : timespec_store(&ts, m), NULL);
3034         if (r < 0)
3035                 return -errno;
3036
3037         return r > 0 ? 1 : 0;
3038 }
3039
3040 _public_ int sd_bus_wait(sd_bus *bus, uint64_t timeout_usec) {
3041
3042         assert_return(bus, -EINVAL);
3043         assert_return(bus = bus_resolve(bus), -ENOPKG);
3044         assert_return(!bus_pid_changed(bus), -ECHILD);
3045
3046         if (bus->state == BUS_CLOSING)
3047                 return 0;
3048
3049         if (!BUS_IS_OPEN(bus->state))
3050                 return -ENOTCONN;
3051
3052         if (bus->rqueue_size > 0)
3053                 return 0;
3054
3055         return bus_poll(bus, false, timeout_usec);
3056 }
3057
3058 _public_ int sd_bus_flush(sd_bus *bus) {
3059         int r;
3060
3061         assert_return(bus, -EINVAL);
3062         assert_return(bus = bus_resolve(bus), -ENOPKG);
3063         assert_return(!bus_pid_changed(bus), -ECHILD);
3064
3065         if (bus->state == BUS_CLOSING)
3066                 return 0;
3067
3068         if (!BUS_IS_OPEN(bus->state))
3069                 return -ENOTCONN;
3070
3071         /* We never were connected? Don't hang in inotify for good, as there's no timeout set for it */
3072         if (bus->state == BUS_WATCH_BIND)
3073                 return -EUNATCH;
3074
3075         r = bus_ensure_running(bus);
3076         if (r < 0)
3077                 return r;
3078
3079         if (bus->wqueue_size <= 0)
3080                 return 0;
3081
3082         for (;;) {
3083                 r = dispatch_wqueue(bus);
3084                 if (r < 0) {
3085                         if (IN_SET(r, -ENOTCONN, -ECONNRESET, -EPIPE, -ESHUTDOWN)) {
3086                                 bus_enter_closing(bus);
3087                                 return -ECONNRESET;
3088                         }
3089
3090                         return r;
3091                 }
3092
3093                 if (bus->wqueue_size <= 0)
3094                         return 0;
3095
3096                 r = bus_poll(bus, false, (uint64_t) -1);
3097                 if (r < 0)
3098                         return r;
3099         }
3100 }
3101
3102 _public_ int sd_bus_add_filter(
3103                 sd_bus *bus,
3104                 sd_bus_slot **slot,
3105                 sd_bus_message_handler_t callback,
3106                 void *userdata) {
3107
3108         sd_bus_slot *s;
3109
3110         assert_return(bus, -EINVAL);
3111         assert_return(bus = bus_resolve(bus), -ENOPKG);
3112         assert_return(callback, -EINVAL);
3113         assert_return(!bus_pid_changed(bus), -ECHILD);
3114
3115         s = bus_slot_allocate(bus, !slot, BUS_FILTER_CALLBACK, sizeof(struct filter_callback), userdata);
3116         if (!s)
3117                 return -ENOMEM;
3118
3119         s->filter_callback.callback = callback;
3120
3121         bus->filter_callbacks_modified = true;
3122         LIST_PREPEND(callbacks, bus->filter_callbacks, &s->filter_callback);
3123
3124         if (slot)
3125                 *slot = s;
3126
3127         return 0;
3128 }
3129
3130 static int add_match_callback(
3131                 sd_bus_message *m,
3132                 void *userdata,
3133                 sd_bus_error *ret_error) {
3134
3135         sd_bus_slot *match_slot = userdata;
3136         bool failed = false;
3137         int r;
3138
3139         assert(m);
3140         assert(match_slot);
3141
3142         sd_bus_slot_ref(match_slot);
3143
3144         if (sd_bus_message_is_method_error(m, NULL)) {
3145                 log_debug_errno(sd_bus_message_get_errno(m),
3146                                 "Unable to add match %s, failing connection: %s",
3147                                 match_slot->match_callback.match_string,
3148                                 sd_bus_message_get_error(m)->message);
3149
3150                 failed = true;
3151         } else
3152                 log_debug("Match %s successfully installed.", match_slot->match_callback.match_string);
3153
3154         if (match_slot->match_callback.install_callback) {
3155                 sd_bus *bus;
3156
3157                 bus = sd_bus_message_get_bus(m);
3158
3159                 /* This function has been called as slot handler, and we want to call another slot handler. Let's
3160                  * update the slot callback metadata temporarily with our own data, and then revert back to the old
3161                  * values. */
3162
3163                 assert(bus->current_slot == match_slot->match_callback.install_slot);
3164                 assert(bus->current_handler == add_match_callback);
3165                 assert(bus->current_userdata == userdata);
3166
3167                 bus->current_slot = match_slot;
3168                 bus->current_handler = match_slot->match_callback.install_callback;
3169                 bus->current_userdata = match_slot->userdata;
3170
3171                 r = match_slot->match_callback.install_callback(m, match_slot->userdata, ret_error);
3172
3173                 bus->current_slot = match_slot->match_callback.install_slot;
3174                 bus->current_handler = add_match_callback;
3175                 bus->current_userdata = userdata;
3176
3177                 match_slot->match_callback.install_slot = sd_bus_slot_unref(match_slot->match_callback.install_slot);
3178         } else {
3179                 if (failed) /* Generic failure handling: destroy the connection */
3180                         bus_enter_closing(sd_bus_message_get_bus(m));
3181
3182                 r = 1;
3183         }
3184
3185         if (failed && match_slot->floating) {
3186                 bus_slot_disconnect(match_slot);
3187                 sd_bus_slot_unref(match_slot);
3188         }
3189
3190         sd_bus_slot_unref(match_slot);
3191
3192         return r;
3193 }
3194
3195 static int bus_add_match_full(
3196                 sd_bus *bus,
3197                 sd_bus_slot **slot,
3198                 bool asynchronous,
3199                 const char *match,
3200                 sd_bus_message_handler_t callback,
3201                 sd_bus_message_handler_t install_callback,
3202                 void *userdata) {
3203
3204         struct bus_match_component *components = NULL;
3205         unsigned n_components = 0;
3206         sd_bus_slot *s = NULL;
3207         int r = 0;
3208
3209         assert_return(bus, -EINVAL);
3210         assert_return(bus = bus_resolve(bus), -ENOPKG);
3211         assert_return(match, -EINVAL);
3212         assert_return(!bus_pid_changed(bus), -ECHILD);
3213
3214         r = bus_match_parse(match, &components, &n_components);
3215         if (r < 0)
3216                 goto finish;
3217
3218         s = bus_slot_allocate(bus, !slot, BUS_MATCH_CALLBACK, sizeof(struct match_callback), userdata);
3219         if (!s) {
3220                 r = -ENOMEM;
3221                 goto finish;
3222         }
3223
3224         s->match_callback.callback = callback;
3225         s->match_callback.install_callback = install_callback;
3226
3227         if (bus->bus_client) {
3228                 enum bus_match_scope scope;
3229
3230                 scope = bus_match_get_scope(components, n_components);
3231
3232                 /* Do not install server-side matches for matches against the local service, interface or bus path. */
3233                 if (scope != BUS_MATCH_LOCAL) {
3234
3235                         /* We store the original match string, so that we can use it to remove the match again. */
3236
3237                         s->match_callback.match_string = strdup(match);
3238                         if (!s->match_callback.match_string) {
3239                                 r = -ENOMEM;
3240                                 goto finish;
3241                         }
3242
3243                         if (asynchronous) {
3244                                 r = bus_add_match_internal_async(bus,
3245                                                                  &s->match_callback.install_slot,
3246                                                                  s->match_callback.match_string,
3247                                                                  add_match_callback,
3248                                                                  s);
3249
3250                                 if (r < 0)
3251                                         return r;
3252
3253                                 /* Make the slot of the match call floating now. We need the reference, but we don't
3254                                  * want that this match pins the bus object, hence we first create it non-floating, but
3255                                  * then make it floating. */
3256                                 r = sd_bus_slot_set_floating(s->match_callback.install_slot, true);
3257                         } else
3258                                 r = bus_add_match_internal(bus, s->match_callback.match_string);
3259                         if (r < 0)
3260                                 goto finish;
3261
3262                         s->match_added = true;
3263                 }
3264         }
3265
3266         bus->match_callbacks_modified = true;
3267         r = bus_match_add(&bus->match_callbacks, components, n_components, &s->match_callback);
3268         if (r < 0)
3269                 goto finish;
3270
3271         if (slot)
3272                 *slot = s;
3273         s = NULL;
3274
3275 finish:
3276         bus_match_parse_free(components, n_components);
3277         sd_bus_slot_unref(s);
3278
3279         return r;
3280 }
3281
3282 #if 0 /// UNNEEDED by elogind
3283 #endif // 0
3284 _public_ int sd_bus_add_match(
3285                 sd_bus *bus,
3286                 sd_bus_slot **slot,
3287                 const char *match,
3288                 sd_bus_message_handler_t callback,
3289                 void *userdata) {
3290
3291         return bus_add_match_full(bus, slot, false, match, callback, NULL, userdata);
3292 }
3293
3294 _public_ int sd_bus_add_match_async(
3295                 sd_bus *bus,
3296                 sd_bus_slot **slot,
3297                 const char *match,
3298                 sd_bus_message_handler_t callback,
3299                 sd_bus_message_handler_t install_callback,
3300                 void *userdata) {
3301
3302         return bus_add_match_full(bus, slot, true, match, callback, install_callback, userdata);
3303 }
3304
3305 bool bus_pid_changed(sd_bus *bus) {
3306         assert(bus);
3307
3308         /* We don't support people creating a bus connection and
3309          * keeping it around over a fork(). Let's complain. */
3310
3311         return bus->original_pid != getpid_cached();
3312 }
3313
3314 static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
3315         sd_bus *bus = userdata;
3316         int r;
3317
3318         assert(bus);
3319
3320         /* Note that this is called both on input_fd, output_fd as well as inotify_fd events */
3321
3322         r = sd_bus_process(bus, NULL);
3323         if (r < 0) {
3324                 log_debug_errno(r, "Processing of bus failed, closing down: %m");
3325                 bus_enter_closing(bus);
3326         }
3327
3328         return 1;
3329 }
3330
3331 static int time_callback(sd_event_source *s, uint64_t usec, void *userdata) {
3332         sd_bus *bus = userdata;
3333         int r;
3334
3335         assert(bus);
3336
3337         r = sd_bus_process(bus, NULL);
3338         if (r < 0) {
3339                 log_debug_errno(r, "Processing of bus failed, closing down: %m");
3340                 bus_enter_closing(bus);
3341         }
3342
3343         return 1;
3344 }
3345
3346 static int prepare_callback(sd_event_source *s, void *userdata) {
3347         sd_bus *bus = userdata;
3348         int r, e;
3349         usec_t until;
3350
3351         assert(s);
3352         assert(bus);
3353
3354         e = sd_bus_get_events(bus);
3355         if (e < 0) {
3356                 r = e;
3357                 goto fail;
3358         }
3359
3360         if (bus->output_fd != bus->input_fd) {
3361
3362                 r = sd_event_source_set_io_events(bus->input_io_event_source, e & POLLIN);
3363                 if (r < 0)
3364                         goto fail;
3365
3366                 r = sd_event_source_set_io_events(bus->output_io_event_source, e & POLLOUT);
3367         } else
3368                 r = sd_event_source_set_io_events(bus->input_io_event_source, e);
3369         if (r < 0)
3370                 goto fail;
3371
3372         r = sd_bus_get_timeout(bus, &until);
3373         if (r < 0)
3374                 goto fail;
3375         if (r > 0) {
3376                 int j;
3377
3378                 j = sd_event_source_set_time(bus->time_event_source, until);
3379                 if (j < 0) {
3380                         r = j;
3381                         goto fail;
3382                 }
3383         }
3384
3385         r = sd_event_source_set_enabled(bus->time_event_source, r > 0);
3386         if (r < 0)
3387                 goto fail;
3388
3389         return 1;
3390
3391 fail:
3392         log_debug_errno(r, "Preparing of bus events failed, closing down: %m");
3393         bus_enter_closing(bus);
3394
3395         return 1;
3396 }
3397
3398 static int quit_callback(sd_event_source *event, void *userdata) {
3399         sd_bus *bus = userdata;
3400
3401         assert(event);
3402
3403         sd_bus_flush(bus);
3404         sd_bus_close(bus);
3405
3406         return 1;
3407 }
3408
3409 int bus_attach_io_events(sd_bus *bus) {
3410         int r;
3411
3412         assert(bus);
3413
3414         if (bus->input_fd < 0)
3415                 return 0;
3416
3417         if (!bus->event)
3418                 return 0;
3419
3420         if (!bus->input_io_event_source) {
3421                 r = sd_event_add_io(bus->event, &bus->input_io_event_source, bus->input_fd, 0, io_callback, bus);
3422                 if (r < 0)
3423                         return r;
3424
3425                 r = sd_event_source_set_prepare(bus->input_io_event_source, prepare_callback);
3426                 if (r < 0)
3427                         return r;
3428
3429                 r = sd_event_source_set_priority(bus->input_io_event_source, bus->event_priority);
3430                 if (r < 0)
3431                         return r;
3432
3433                 r = sd_event_source_set_description(bus->input_io_event_source, "bus-input");
3434         } else
3435                 r = sd_event_source_set_io_fd(bus->input_io_event_source, bus->input_fd);
3436
3437         if (r < 0)
3438                 return r;
3439
3440         if (bus->output_fd != bus->input_fd) {
3441                 assert(bus->output_fd >= 0);
3442
3443                 if (!bus->output_io_event_source) {
3444                         r = sd_event_add_io(bus->event, &bus->output_io_event_source, bus->output_fd, 0, io_callback, bus);
3445                         if (r < 0)
3446                                 return r;
3447
3448                         r = sd_event_source_set_priority(bus->output_io_event_source, bus->event_priority);
3449                         if (r < 0)
3450                                 return r;
3451
3452                         r = sd_event_source_set_description(bus->input_io_event_source, "bus-output");
3453                 } else
3454                         r = sd_event_source_set_io_fd(bus->output_io_event_source, bus->output_fd);
3455
3456                 if (r < 0)
3457                         return r;
3458         }
3459
3460         return 0;
3461 }
3462
3463 static void bus_detach_io_events(sd_bus *bus) {
3464         assert(bus);
3465
3466         if (bus->input_io_event_source) {
3467                 sd_event_source_set_enabled(bus->input_io_event_source, SD_EVENT_OFF);
3468                 bus->input_io_event_source = sd_event_source_unref(bus->input_io_event_source);
3469         }
3470
3471         if (bus->output_io_event_source) {
3472                 sd_event_source_set_enabled(bus->output_io_event_source, SD_EVENT_OFF);
3473                 bus->output_io_event_source = sd_event_source_unref(bus->output_io_event_source);
3474         }
3475 }
3476
3477 int bus_attach_inotify_event(sd_bus *bus) {
3478         int r;
3479
3480         assert(bus);
3481
3482         if (bus->inotify_fd < 0)
3483                 return 0;
3484
3485         if (!bus->event)
3486                 return 0;
3487
3488         if (!bus->inotify_event_source) {
3489                 r = sd_event_add_io(bus->event, &bus->inotify_event_source, bus->inotify_fd, EPOLLIN, io_callback, bus);
3490                 if (r < 0)
3491                         return r;
3492
3493                 r = sd_event_source_set_priority(bus->inotify_event_source, bus->event_priority);
3494                 if (r < 0)
3495                         return r;
3496
3497                 r = sd_event_source_set_description(bus->inotify_event_source, "bus-inotify");
3498         } else
3499                 r = sd_event_source_set_io_fd(bus->inotify_event_source, bus->inotify_fd);
3500         if (r < 0)
3501                 return r;
3502
3503         return 0;
3504 }
3505
3506 static void bus_detach_inotify_event(sd_bus *bus) {
3507         assert(bus);
3508
3509         if (bus->inotify_event_source) {
3510                 sd_event_source_set_enabled(bus->inotify_event_source, SD_EVENT_OFF);
3511                 bus->inotify_event_source = sd_event_source_unref(bus->inotify_event_source);
3512         }
3513 }
3514
3515 _public_ int sd_bus_attach_event(sd_bus *bus, sd_event *event, int priority) {
3516         int r;
3517
3518         assert_return(bus, -EINVAL);
3519         assert_return(bus = bus_resolve(bus), -ENOPKG);
3520         assert_return(!bus->event, -EBUSY);
3521
3522         assert(!bus->input_io_event_source);
3523         assert(!bus->output_io_event_source);
3524         assert(!bus->time_event_source);
3525
3526         if (event)
3527                 bus->event = sd_event_ref(event);
3528         else  {
3529                 r = sd_event_default(&bus->event);
3530                 if (r < 0)
3531                         return r;
3532         }
3533
3534         bus->event_priority = priority;
3535
3536         r = sd_event_add_time(bus->event, &bus->time_event_source, CLOCK_MONOTONIC, 0, 0, time_callback, bus);
3537         if (r < 0)
3538                 goto fail;
3539
3540         r = sd_event_source_set_priority(bus->time_event_source, priority);
3541         if (r < 0)
3542                 goto fail;
3543
3544         r = sd_event_source_set_description(bus->time_event_source, "bus-time");
3545         if (r < 0)
3546                 goto fail;
3547
3548         r = sd_event_add_exit(bus->event, &bus->quit_event_source, quit_callback, bus);
3549         if (r < 0)
3550                 goto fail;
3551
3552         r = sd_event_source_set_description(bus->quit_event_source, "bus-exit");
3553         if (r < 0)
3554                 goto fail;
3555
3556         r = bus_attach_io_events(bus);
3557         if (r < 0)
3558                 goto fail;
3559
3560         r = bus_attach_inotify_event(bus);
3561         if (r < 0)
3562                 goto fail;
3563
3564         return 0;
3565
3566 fail:
3567         sd_bus_detach_event(bus);
3568         return r;
3569 }
3570
3571 _public_ int sd_bus_detach_event(sd_bus *bus) {
3572         assert_return(bus, -EINVAL);
3573         assert_return(bus = bus_resolve(bus), -ENOPKG);
3574
3575         if (!bus->event)
3576                 return 0;
3577
3578         bus_detach_io_events(bus);
3579         bus_detach_inotify_event(bus);
3580
3581         if (bus->time_event_source) {
3582                 sd_event_source_set_enabled(bus->time_event_source, SD_EVENT_OFF);
3583                 bus->time_event_source = sd_event_source_unref(bus->time_event_source);
3584         }
3585
3586         if (bus->quit_event_source) {
3587                 sd_event_source_set_enabled(bus->quit_event_source, SD_EVENT_OFF);
3588                 bus->quit_event_source = sd_event_source_unref(bus->quit_event_source);
3589         }
3590
3591         bus->event = sd_event_unref(bus->event);
3592         return 1;
3593 }
3594
3595 _public_ sd_event* sd_bus_get_event(sd_bus *bus) {
3596         assert_return(bus, NULL);
3597
3598         return bus->event;
3599 }
3600
3601 _public_ sd_bus_message* sd_bus_get_current_message(sd_bus *bus) {
3602         assert_return(bus, NULL);
3603
3604         return bus->current_message;
3605 }
3606
3607 _public_ sd_bus_slot* sd_bus_get_current_slot(sd_bus *bus) {
3608         assert_return(bus, NULL);
3609
3610         return bus->current_slot;
3611 }
3612
3613 _public_ sd_bus_message_handler_t sd_bus_get_current_handler(sd_bus *bus) {
3614         assert_return(bus, NULL);
3615
3616         return bus->current_handler;
3617 }
3618
3619 _public_ void* sd_bus_get_current_userdata(sd_bus *bus) {
3620         assert_return(bus, NULL);
3621
3622         return bus->current_userdata;
3623 }
3624
3625 static int bus_default(int (*bus_open)(sd_bus **), sd_bus **default_bus, sd_bus **ret) {
3626         sd_bus *b = NULL;
3627         int r;
3628
3629         assert(bus_open);
3630         assert(default_bus);
3631
3632         if (!ret)
3633                 return !!*default_bus;
3634
3635         if (*default_bus) {
3636                 *ret = sd_bus_ref(*default_bus);
3637                 return 0;
3638         }
3639
3640         r = bus_open(&b);
3641         if (r < 0)
3642                 return r;
3643
3644         b->default_bus_ptr = default_bus;
3645         b->tid = gettid();
3646         *default_bus = b;
3647
3648         *ret = b;
3649         return 1;
3650 }
3651
3652 _public_ int sd_bus_default_system(sd_bus **ret) {
3653         return bus_default(sd_bus_open_system, &default_system_bus, ret);
3654 }
3655
3656 _public_ int sd_bus_default_user(sd_bus **ret) {
3657 #if 0 /// elogind does not support user buses
3658         return bus_default(sd_bus_open_user, &default_user_bus, ret);
3659 #else
3660         return sd_bus_default_system(ret);
3661 #endif // 0
3662 }
3663
3664 _public_ int sd_bus_default(sd_bus **ret) {
3665         int (*bus_open)(sd_bus **) = NULL;
3666         sd_bus **busp;
3667
3668         busp = bus_choose_default(&bus_open);
3669         return bus_default(bus_open, busp, ret);
3670 }
3671
3672 _public_ int sd_bus_get_tid(sd_bus *b, pid_t *tid) {
3673         assert_return(b, -EINVAL);
3674         assert_return(tid, -EINVAL);
3675         assert_return(!bus_pid_changed(b), -ECHILD);
3676
3677         if (b->tid != 0) {
3678                 *tid = b->tid;
3679                 return 0;
3680         }
3681
3682         if (b->event)
3683                 return sd_event_get_tid(b->event, tid);
3684
3685         return -ENXIO;
3686 }
3687
3688 _public_ int sd_bus_path_encode(const char *prefix, const char *external_id, char **ret_path) {
3689         _cleanup_free_ char *e = NULL;
3690         char *ret;
3691
3692         assert_return(object_path_is_valid(prefix), -EINVAL);
3693         assert_return(external_id, -EINVAL);
3694         assert_return(ret_path, -EINVAL);
3695
3696         e = bus_label_escape(external_id);
3697         if (!e)
3698                 return -ENOMEM;
3699
3700         ret = strjoin(prefix, "/", e);
3701         if (!ret)
3702                 return -ENOMEM;
3703
3704         *ret_path = ret;
3705         return 0;
3706 }
3707
3708 _public_ int sd_bus_path_decode(const char *path, const char *prefix, char **external_id) {
3709         const char *e;
3710         char *ret;
3711
3712         assert_return(object_path_is_valid(path), -EINVAL);
3713         assert_return(object_path_is_valid(prefix), -EINVAL);
3714         assert_return(external_id, -EINVAL);
3715
3716         e = object_path_startswith(path, prefix);
3717         if (!e) {
3718                 *external_id = NULL;
3719                 return 0;
3720         }
3721
3722         ret = bus_label_unescape(e);
3723         if (!ret)
3724                 return -ENOMEM;
3725
3726         *external_id = ret;
3727         return 1;
3728 }
3729
3730 _public_ int sd_bus_path_encode_many(char **out, const char *path_template, ...) {
3731         _cleanup_strv_free_ char **labels = NULL;
3732         char *path, *path_pos, **label_pos;
3733         const char *sep, *template_pos;
3734         size_t path_length;
3735         va_list list;
3736         int r;
3737
3738         assert_return(out, -EINVAL);
3739         assert_return(path_template, -EINVAL);
3740
3741         path_length = strlen(path_template);
3742
3743         va_start(list, path_template);
3744         for (sep = strchr(path_template, '%'); sep; sep = strchr(sep + 1, '%')) {
3745                 const char *arg;
3746                 char *label;
3747
3748                 arg = va_arg(list, const char *);
3749                 if (!arg) {
3750                         va_end(list);
3751                         return -EINVAL;
3752                 }
3753
3754                 label = bus_label_escape(arg);
3755                 if (!label) {
3756                         va_end(list);
3757                         return -ENOMEM;
3758                 }
3759
3760                 r = strv_consume(&labels, label);
3761                 if (r < 0) {
3762                         va_end(list);
3763                         return r;
3764                 }
3765
3766                 /* add label length, but account for the format character */
3767                 path_length += strlen(label) - 1;
3768         }
3769         va_end(list);
3770
3771         path = malloc(path_length + 1);
3772         if (!path)
3773                 return -ENOMEM;
3774
3775         path_pos = path;
3776         label_pos = labels;
3777
3778         for (template_pos = path_template; *template_pos; ) {
3779                 sep = strchrnul(template_pos, '%');
3780                 path_pos = mempcpy(path_pos, template_pos, sep - template_pos);
3781                 if (!*sep)
3782                         break;
3783
3784                 path_pos = stpcpy(path_pos, *label_pos++);
3785                 template_pos = sep + 1;
3786         }
3787
3788         *path_pos = 0;
3789         *out = path;
3790         return 0;
3791 }
3792
3793 _public_ int sd_bus_path_decode_many(const char *path, const char *path_template, ...) {
3794         _cleanup_strv_free_ char **labels = NULL;
3795         const char *template_pos, *path_pos;
3796         char **label_pos;
3797         va_list list;
3798         int r;
3799
3800         /*
3801          * This decodes an object-path based on a template argument. The
3802          * template consists of a verbatim path, optionally including special
3803          * directives:
3804          *
3805          *   - Each occurrence of '%' in the template matches an arbitrary
3806          *     substring of a label in the given path. At most one such
3807          *     directive is allowed per label. For each such directive, the
3808          *     caller must provide an output parameter (char **) via va_arg. If
3809          *     NULL is passed, the given label is verified, but not returned.
3810          *     For each matched label, the *decoded* label is stored in the
3811          *     passed output argument, and the caller is responsible to free
3812          *     it. Note that the output arguments are only modified if the
3813          *     actualy path matched the template. Otherwise, they're left
3814          *     untouched.
3815          *
3816          * This function returns <0 on error, 0 if the path does not match the
3817          * template, 1 if it matched.
3818          */
3819
3820         assert_return(path, -EINVAL);
3821         assert_return(path_template, -EINVAL);
3822
3823         path_pos = path;
3824
3825         for (template_pos = path_template; *template_pos; ) {
3826                 const char *sep;
3827                 size_t length;
3828                 char *label;
3829
3830                 /* verify everything until the next '%' matches verbatim */
3831                 sep = strchrnul(template_pos, '%');
3832                 length = sep - template_pos;
3833                 if (strncmp(path_pos, template_pos, length))
3834                         return 0;
3835
3836                 path_pos += length;
3837                 template_pos += length;
3838
3839                 if (!*template_pos)
3840                         break;
3841
3842                 /* We found the next '%' character. Everything up until here
3843                  * matched. We now skip ahead to the end of this label and make
3844                  * sure it matches the tail of the label in the path. Then we
3845                  * decode the string in-between and save it for later use. */
3846
3847                 ++template_pos; /* skip over '%' */
3848
3849                 sep = strchrnul(template_pos, '/');
3850                 length = sep - template_pos; /* length of suffix to match verbatim */
3851
3852                 /* verify the suffixes match */
3853                 sep = strchrnul(path_pos, '/');
3854                 if (sep - path_pos < (ssize_t)length ||
3855                     strncmp(sep - length, template_pos, length))
3856                         return 0;
3857
3858                 template_pos += length; /* skip over matched label */
3859                 length = sep - path_pos - length; /* length of sub-label to decode */
3860
3861                 /* store unescaped label for later use */
3862                 label = bus_label_unescape_n(path_pos, length);
3863                 if (!label)
3864                         return -ENOMEM;
3865
3866                 r = strv_consume(&labels, label);
3867                 if (r < 0)
3868                         return r;
3869
3870                 path_pos = sep; /* skip decoded label and suffix */
3871         }
3872
3873         /* end of template must match end of path */
3874         if (*path_pos)
3875                 return 0;
3876
3877         /* copy the labels over to the caller */
3878         va_start(list, path_template);
3879         for (label_pos = labels; label_pos && *label_pos; ++label_pos) {
3880                 char **arg;
3881
3882                 arg = va_arg(list, char **);
3883                 if (arg)
3884                         *arg = *label_pos;
3885                 else
3886                         free(*label_pos);
3887         }
3888         va_end(list);
3889
3890         labels = mfree(labels);
3891         return 1;
3892 }
3893
3894 _public_ int sd_bus_try_close(sd_bus *bus) {
3895         assert_return(bus, -EINVAL);
3896         assert_return(bus = bus_resolve(bus), -ENOPKG);
3897         assert_return(!bus_pid_changed(bus), -ECHILD);
3898
3899         return -EOPNOTSUPP;
3900 }
3901
3902 _public_ int sd_bus_get_description(sd_bus *bus, const char **description) {
3903         assert_return(bus, -EINVAL);
3904         assert_return(bus = bus_resolve(bus), -ENOPKG);
3905         assert_return(description, -EINVAL);
3906         assert_return(bus->description, -ENXIO);
3907         assert_return(!bus_pid_changed(bus), -ECHILD);
3908
3909         if (bus->description)
3910                 *description = bus->description;
3911         else if (bus->is_system)
3912                 *description = "system";
3913         else if (bus->is_user)
3914                 *description = "user";
3915         else
3916                 *description = NULL;
3917
3918         return 0;
3919 }
3920
3921 int bus_get_root_path(sd_bus *bus) {
3922         int r;
3923
3924         if (bus->cgroup_root)
3925                 return 0;
3926
3927         r = cg_get_root_path(&bus->cgroup_root);
3928         if (r == -ENOENT) {
3929                 bus->cgroup_root = strdup("/");
3930                 if (!bus->cgroup_root)
3931                         return -ENOMEM;
3932
3933                 r = 0;
3934         }
3935
3936         return r;
3937 }
3938
3939 _public_ int sd_bus_get_scope(sd_bus *bus, const char **scope) {
3940         assert_return(bus, -EINVAL);
3941         assert_return(bus = bus_resolve(bus), -ENOPKG);
3942         assert_return(scope, -EINVAL);
3943         assert_return(!bus_pid_changed(bus), -ECHILD);
3944
3945         if (bus->is_user) {
3946                 *scope = "user";
3947                 return 0;
3948         }
3949
3950         if (bus->is_system) {
3951                 *scope = "system";
3952                 return 0;
3953         }
3954
3955         return -ENODATA;
3956 }
3957
3958 _public_ int sd_bus_get_address(sd_bus *bus, const char **address) {
3959
3960         assert_return(bus, -EINVAL);
3961         assert_return(bus = bus_resolve(bus), -ENOPKG);
3962         assert_return(address, -EINVAL);
3963         assert_return(!bus_pid_changed(bus), -ECHILD);
3964
3965         if (bus->address) {
3966                 *address = bus->address;
3967                 return 0;
3968         }
3969
3970         return -ENODATA;
3971 }
3972
3973 _public_ int sd_bus_get_creds_mask(sd_bus *bus, uint64_t *mask) {
3974         assert_return(bus, -EINVAL);
3975         assert_return(bus = bus_resolve(bus), -ENOPKG);
3976         assert_return(mask, -EINVAL);
3977         assert_return(!bus_pid_changed(bus), -ECHILD);
3978
3979         *mask = bus->creds_mask;
3980         return 0;
3981 }
3982
3983 _public_ int sd_bus_is_bus_client(sd_bus *bus) {
3984         assert_return(bus, -EINVAL);
3985         assert_return(bus = bus_resolve(bus), -ENOPKG);
3986         assert_return(!bus_pid_changed(bus), -ECHILD);
3987
3988         return bus->bus_client;
3989 }
3990
3991 _public_ int sd_bus_is_server(sd_bus *bus) {
3992         assert_return(bus, -EINVAL);
3993         assert_return(bus = bus_resolve(bus), -ENOPKG);
3994         assert_return(!bus_pid_changed(bus), -ECHILD);
3995
3996         return bus->is_server;
3997 }
3998
3999 _public_ int sd_bus_is_anonymous(sd_bus *bus) {
4000         assert_return(bus, -EINVAL);
4001         assert_return(bus = bus_resolve(bus), -ENOPKG);
4002         assert_return(!bus_pid_changed(bus), -ECHILD);
4003
4004         return bus->anonymous_auth;
4005 }
4006
4007 _public_ int sd_bus_is_trusted(sd_bus *bus) {
4008         assert_return(bus, -EINVAL);
4009         assert_return(bus = bus_resolve(bus), -ENOPKG);
4010         assert_return(!bus_pid_changed(bus), -ECHILD);
4011
4012         return bus->trusted;
4013 }
4014
4015 _public_ int sd_bus_is_monitor(sd_bus *bus) {
4016         assert_return(bus, -EINVAL);
4017         assert_return(bus = bus_resolve(bus), -ENOPKG);
4018         assert_return(!bus_pid_changed(bus), -ECHILD);
4019
4020         return bus->is_monitor;
4021 }
4022
4023 static void flush_close(sd_bus *bus) {
4024         if (!bus)
4025                 return;
4026
4027         /* Flushes and closes the specified bus. We take a ref before,
4028          * to ensure the flushing does not cause the bus to be
4029          * unreferenced. */
4030
4031         sd_bus_flush_close_unref(sd_bus_ref(bus));
4032 }
4033
4034 _public_ void sd_bus_default_flush_close(void) {
4035         flush_close(default_starter_bus);
4036 #if 0 /// elogind does not support user buses
4037         flush_close(default_user_bus);
4038 #endif // 0
4039         flush_close(default_system_bus);
4040 }
4041
4042 _public_ int sd_bus_set_exit_on_disconnect(sd_bus *bus, int b) {
4043         assert_return(bus, -EINVAL);
4044         assert_return(bus = bus_resolve(bus), -ENOPKG);
4045
4046         /* Turns on exit-on-disconnect, and triggers it immediately if the bus connection was already
4047          * disconnected. Note that this is triggered exclusively on disconnections triggered by the server side, never
4048          * from the client side. */
4049         bus->exit_on_disconnect = b;
4050
4051         /* If the exit condition was triggered already, exit immediately. */
4052         return bus_exit_now(bus);
4053 }
4054
4055 _public_ int sd_bus_get_exit_on_disconnect(sd_bus *bus) {
4056         assert_return(bus, -EINVAL);
4057         assert_return(bus = bus_resolve(bus), -ENOPKG);
4058
4059         return bus->exit_on_disconnect;
4060 }
4061
4062 _public_ int sd_bus_set_sender(sd_bus *bus, const char *sender) {
4063         assert_return(bus, -EINVAL);
4064         assert_return(bus = bus_resolve(bus), -ENOPKG);
4065         assert_return(!bus->bus_client, -EPERM);
4066         assert_return(!sender || service_name_is_valid(sender), -EINVAL);
4067
4068         return free_and_strdup(&bus->patch_sender, sender);
4069 }
4070
4071 _public_ int sd_bus_get_sender(sd_bus *bus, const char **ret) {
4072         assert_return(bus, -EINVAL);
4073         assert_return(bus = bus_resolve(bus), -ENOPKG);
4074         assert_return(ret, -EINVAL);
4075
4076         if (!bus->patch_sender)
4077                 return -ENODATA;
4078
4079         *ret = bus->patch_sender;
4080         return 0;
4081 }
4082
4083 _public_ int sd_bus_get_n_queued_read(sd_bus *bus, uint64_t *ret) {
4084         assert_return(bus, -EINVAL);
4085         assert_return(bus = bus_resolve(bus), -ENOPKG);
4086         assert_return(!bus_pid_changed(bus), -ECHILD);
4087         assert_return(ret, -EINVAL);
4088
4089         *ret = bus->rqueue_size;
4090         return 0;
4091 }
4092
4093 _public_ int sd_bus_get_n_queued_write(sd_bus *bus, uint64_t *ret) {
4094         assert_return(bus, -EINVAL);
4095         assert_return(bus = bus_resolve(bus), -ENOPKG);
4096         assert_return(!bus_pid_changed(bus), -ECHILD);
4097         assert_return(ret, -EINVAL);
4098
4099         *ret = bus->wqueue_size;
4100         return 0;
4101 }