Debian Codegraph @

src/libsystemd/sd-bus/sd-bus.c

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