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