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