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