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