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