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