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