]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/bus-util.c
Merge pull request #31039 from AdrianVovk/slice-freeze-thaw
[thirdparty/systemd.git] / src / shared / bus-util.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <inttypes.h>
6 #include <stdlib.h>
7 #include <sys/ioctl.h>
8 #include <sys/resource.h>
9 #include <sys/socket.h>
10 #include <unistd.h>
11
12 #include "sd-bus.h"
13 #include "sd-daemon.h"
14 #include "sd-event.h"
15 #include "sd-id128.h"
16
17 #include "bus-common-errors.h"
18 #include "bus-internal.h"
19 #include "bus-label.h"
20 #include "bus-util.h"
21 #include "daemon-util.h"
22 #include "data-fd-util.h"
23 #include "fd-util.h"
24 #include "memstream-util.h"
25 #include "path-util.h"
26 #include "socket-util.h"
27 #include "stdio-util.h"
28
29 static int name_owner_change_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
30 sd_event *e = ASSERT_PTR(userdata);
31
32 assert(m);
33
34 sd_bus_close(sd_bus_message_get_bus(m));
35 sd_event_exit(e, 0);
36
37 return 1;
38 }
39
40 int bus_log_address_error(int r, BusTransport transport) {
41 bool hint = transport == BUS_TRANSPORT_LOCAL && r == -ENOMEDIUM;
42
43 return log_error_errno(r,
44 hint ? "Failed to set bus address: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined (consider using --machine=<user>@.host --user to connect to bus of other user)" :
45 "Failed to set bus address: %m");
46 }
47
48 int bus_log_connect_error(int r, BusTransport transport) {
49 bool hint_vars = transport == BUS_TRANSPORT_LOCAL && r == -ENOMEDIUM,
50 hint_addr = transport == BUS_TRANSPORT_LOCAL && ERRNO_IS_PRIVILEGE(r);
51
52 return log_error_errno(r,
53 r == hint_vars ? "Failed to connect to bus: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined (consider using --machine=<user>@.host --user to connect to bus of other user)" :
54 r == hint_addr ? "Failed to connect to bus: Operation not permitted (consider using --machine=<user>@.host --user to connect to bus of other user)" :
55 "Failed to connect to bus: %m");
56 }
57
58 int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name) {
59 const char *match;
60 const char *unique;
61 int r;
62
63 assert(e);
64 assert(bus);
65 assert(name);
66
67 /* We unregister the name here and then wait for the
68 * NameOwnerChanged signal for this event to arrive before we
69 * quit. We do this in order to make sure that any queued
70 * requests are still processed before we really exit. */
71
72 r = sd_bus_get_unique_name(bus, &unique);
73 if (r < 0)
74 return r;
75
76 match = strjoina(
77 "sender='org.freedesktop.DBus',"
78 "type='signal',"
79 "interface='org.freedesktop.DBus',"
80 "member='NameOwnerChanged',"
81 "path='/org/freedesktop/DBus',"
82 "arg0='", name, "',",
83 "arg1='", unique, "',",
84 "arg2=''");
85
86 r = sd_bus_add_match_async(bus, NULL, match, name_owner_change_callback, NULL, e);
87 if (r < 0)
88 return r;
89
90 r = sd_bus_release_name_async(bus, NULL, name, NULL, NULL);
91 if (r < 0)
92 return r;
93
94 return 0;
95 }
96
97 int bus_event_loop_with_idle(
98 sd_event *e,
99 sd_bus *bus,
100 const char *name,
101 usec_t timeout,
102 check_idle_t check_idle,
103 void *userdata) {
104
105 bool exiting = false;
106 int r, code;
107
108 assert(e);
109 assert(bus);
110 assert(name);
111
112 for (;;) {
113 bool idle;
114
115 r = sd_event_get_state(e);
116 if (r < 0)
117 return r;
118 if (r == SD_EVENT_FINISHED)
119 break;
120
121 if (check_idle)
122 idle = check_idle(userdata);
123 else
124 idle = true;
125
126 r = sd_event_run(e, exiting || !idle ? UINT64_MAX : timeout);
127 if (r < 0)
128 return r;
129
130 if (r == 0 && !exiting && idle) {
131 /* Inform the service manager that we are going down, so that it will queue all
132 * further start requests, instead of assuming we are still running. */
133 (void) sd_notify(false, NOTIFY_STOPPING);
134
135 r = bus_async_unregister_and_exit(e, bus, name);
136 if (r < 0)
137 return r;
138
139 exiting = true;
140 }
141 }
142
143 r = sd_event_get_exit_code(e, &code);
144 if (r < 0)
145 return r;
146
147 return code;
148 }
149
150 int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error) {
151 _cleanup_(sd_bus_message_unrefp) sd_bus_message *rep = NULL;
152 int r, has_owner = 0;
153
154 assert(c);
155 assert(name);
156
157 r = sd_bus_call_method(c,
158 "org.freedesktop.DBus",
159 "/org/freedesktop/dbus",
160 "org.freedesktop.DBus",
161 "NameHasOwner",
162 error,
163 &rep,
164 "s",
165 name);
166 if (r < 0)
167 return r;
168
169 r = sd_bus_message_read_basic(rep, 'b', &has_owner);
170 if (r < 0)
171 return sd_bus_error_set_errno(error, r);
172
173 return has_owner;
174 }
175
176 bool bus_error_is_unknown_service(const sd_bus_error *error) {
177 return sd_bus_error_has_names(error,
178 SD_BUS_ERROR_SERVICE_UNKNOWN,
179 SD_BUS_ERROR_NAME_HAS_NO_OWNER,
180 BUS_ERROR_NO_SUCH_UNIT);
181 }
182
183 int bus_check_peercred(sd_bus *c) {
184 struct ucred ucred;
185 int fd, r;
186
187 assert(c);
188
189 fd = sd_bus_get_fd(c);
190 if (fd < 0)
191 return fd;
192
193 r = getpeercred(fd, &ucred);
194 if (r < 0)
195 return r;
196
197 if (ucred.uid != 0 && ucred.uid != geteuid())
198 return -EPERM;
199
200 return 1;
201 }
202
203 int bus_connect_system_systemd(sd_bus **ret_bus) {
204 _cleanup_(sd_bus_close_unrefp) sd_bus *bus = NULL;
205 int r;
206
207 assert(ret_bus);
208
209 if (geteuid() != 0)
210 return sd_bus_default_system(ret_bus);
211
212 /* If we are root then let's talk directly to the system
213 * instance, instead of going via the bus */
214
215 r = sd_bus_new(&bus);
216 if (r < 0)
217 return r;
218
219 r = sd_bus_set_address(bus, "unix:path=/run/systemd/private");
220 if (r < 0)
221 return r;
222
223 r = sd_bus_start(bus);
224 if (r < 0)
225 return sd_bus_default_system(ret_bus);
226
227 r = bus_check_peercred(bus);
228 if (r < 0)
229 return r;
230
231 *ret_bus = TAKE_PTR(bus);
232 return 0;
233 }
234
235 int bus_connect_user_systemd(sd_bus **ret_bus) {
236 _cleanup_(sd_bus_close_unrefp) sd_bus *bus = NULL;
237 _cleanup_free_ char *ee = NULL;
238 const char *e;
239 int r;
240
241 assert(ret_bus);
242
243 e = secure_getenv("XDG_RUNTIME_DIR");
244 if (!e)
245 return sd_bus_default_user(ret_bus);
246
247 ee = bus_address_escape(e);
248 if (!ee)
249 return -ENOMEM;
250
251 r = sd_bus_new(&bus);
252 if (r < 0)
253 return r;
254
255 bus->address = strjoin("unix:path=", ee, "/systemd/private");
256 if (!bus->address)
257 return -ENOMEM;
258
259 r = sd_bus_start(bus);
260 if (r < 0)
261 return sd_bus_default_user(ret_bus);
262
263 r = bus_check_peercred(bus);
264 if (r < 0)
265 return r;
266
267 *ret_bus = TAKE_PTR(bus);
268 return 0;
269 }
270
271 int bus_connect_transport(
272 BusTransport transport,
273 const char *host,
274 RuntimeScope runtime_scope,
275 sd_bus **ret) {
276
277 _cleanup_(sd_bus_close_unrefp) sd_bus *bus = NULL;
278 int r;
279
280 assert(transport >= 0);
281 assert(transport < _BUS_TRANSPORT_MAX);
282 assert(ret);
283
284 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
285 assert_return(transport != BUS_TRANSPORT_REMOTE || runtime_scope == RUNTIME_SCOPE_SYSTEM, -EOPNOTSUPP);
286
287 switch (transport) {
288
289 case BUS_TRANSPORT_LOCAL:
290
291 switch (runtime_scope) {
292
293 case RUNTIME_SCOPE_USER:
294 r = sd_bus_default_user(&bus);
295 break;
296
297 case RUNTIME_SCOPE_SYSTEM:
298 if (sd_booted() <= 0)
299 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
300 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN),
301 "System has not been booted with systemd as init system (PID 1). Can't operate.");
302 r = sd_bus_default_system(&bus);
303 break;
304
305 default:
306 assert_not_reached();
307 }
308 break;
309
310 case BUS_TRANSPORT_REMOTE:
311 r = sd_bus_open_system_remote(&bus, host);
312 break;
313
314 case BUS_TRANSPORT_MACHINE:
315
316 switch (runtime_scope) {
317
318 case RUNTIME_SCOPE_USER:
319 r = sd_bus_open_user_machine(&bus, host);
320 break;
321
322 case RUNTIME_SCOPE_SYSTEM:
323 r = sd_bus_open_system_machine(&bus, host);
324 break;
325
326 default:
327 assert_not_reached();
328 }
329
330 break;
331
332 default:
333 assert_not_reached();
334 }
335 if (r < 0)
336 return r;
337
338 r = sd_bus_set_exit_on_disconnect(bus, true);
339 if (r < 0)
340 return r;
341
342 *ret = TAKE_PTR(bus);
343 return 0;
344 }
345
346 int bus_connect_transport_systemd(BusTransport transport, const char *host, RuntimeScope runtime_scope, sd_bus **bus) {
347 assert(transport >= 0);
348 assert(transport < _BUS_TRANSPORT_MAX);
349 assert(bus);
350
351 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
352 assert_return(transport == BUS_TRANSPORT_LOCAL || runtime_scope == RUNTIME_SCOPE_SYSTEM, -EOPNOTSUPP);
353
354 switch (transport) {
355
356 case BUS_TRANSPORT_LOCAL:
357 switch (runtime_scope) {
358
359 case RUNTIME_SCOPE_USER:
360 return bus_connect_user_systemd(bus);
361
362 case RUNTIME_SCOPE_SYSTEM:
363 if (sd_booted() <= 0)
364 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
365 return log_error_errno(SYNTHETIC_ERRNO(EHOSTDOWN),
366 "System has not been booted with systemd as init system (PID 1). Can't operate.");
367 return bus_connect_system_systemd(bus);
368
369 default:
370 assert_not_reached();
371 }
372
373 break;
374
375 case BUS_TRANSPORT_REMOTE:
376 return sd_bus_open_system_remote(bus, host);
377
378 case BUS_TRANSPORT_MACHINE:
379 return sd_bus_open_system_machine(bus, host);
380
381 default:
382 assert_not_reached();
383 }
384 }
385
386 /**
387 * bus_path_encode_unique() - encode unique object path
388 * @b: bus connection or NULL
389 * @prefix: object path prefix
390 * @sender_id: unique-name of client, or NULL
391 * @external_id: external ID to be chosen by client, or NULL
392 * @ret_path: storage for encoded object path pointer
393 *
394 * Whenever we provide a bus API that allows clients to create and manage
395 * server-side objects, we need to provide a unique name for these objects. If
396 * we let the server choose the name, we suffer from a race condition: If a
397 * client creates an object asynchronously, it cannot destroy that object until
398 * it received the method reply. It cannot know the name of the new object,
399 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
400 *
401 * Therefore, many APIs allow the client to choose the unique name for newly
402 * created objects. There're two problems to solve, though:
403 * 1) Object names are usually defined via dbus object paths, which are
404 * usually globally namespaced. Therefore, multiple clients must be able
405 * to choose unique object names without interference.
406 * 2) If multiple libraries share the same bus connection, they must be
407 * able to choose unique object names without interference.
408 * The first problem is solved easily by prefixing a name with the
409 * unique-bus-name of a connection. The server side must enforce this and
410 * reject any other name. The second problem is solved by providing unique
411 * suffixes from within sd-bus.
412 *
413 * This helper allows clients to create unique object-paths. It uses the
414 * template '/prefix/sender_id/external_id' and returns the new path in
415 * @ret_path (must be freed by the caller).
416 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
417 * NULL, this function allocates a unique suffix via @b (by requesting a new
418 * cookie). If both @sender_id and @external_id are given, @b can be passed as
419 * NULL.
420 *
421 * Returns: 0 on success, negative error code on failure.
422 */
423 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
424 _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
425 char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
426 int r;
427
428 assert_return(b || (sender_id && external_id), -EINVAL);
429 assert_return(sd_bus_object_path_is_valid(prefix), -EINVAL);
430 assert_return(ret_path, -EINVAL);
431
432 if (!sender_id) {
433 r = sd_bus_get_unique_name(b, &sender_id);
434 if (r < 0)
435 return r;
436 }
437
438 if (!external_id) {
439 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
440 external_id = external_buf;
441 }
442
443 sender_label = bus_label_escape(sender_id);
444 if (!sender_label)
445 return -ENOMEM;
446
447 external_label = bus_label_escape(external_id);
448 if (!external_label)
449 return -ENOMEM;
450
451 p = path_join(prefix, sender_label, external_label);
452 if (!p)
453 return -ENOMEM;
454
455 *ret_path = p;
456 return 0;
457 }
458
459 /**
460 * bus_path_decode_unique() - decode unique object path
461 * @path: object path to decode
462 * @prefix: object path prefix
463 * @ret_sender: output parameter for sender-id label
464 * @ret_external: output parameter for external-id label
465 *
466 * This does the reverse of bus_path_encode_unique() (see its description for
467 * details). Both trailing labels, sender-id and external-id, are unescaped and
468 * returned in the given output parameters (the caller must free them).
469 *
470 * Note that this function returns 0 if the path does not match the template
471 * (see bus_path_encode_unique()), 1 if it matched.
472 *
473 * Returns: Negative error code on failure, 0 if the given object path does not
474 * match the template (return parameters are set to NULL), 1 if it was
475 * parsed successfully (return parameters contain allocated labels).
476 */
477 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
478 const char *p, *q;
479 char *sender, *external;
480
481 assert(sd_bus_object_path_is_valid(path));
482 assert(sd_bus_object_path_is_valid(prefix));
483 assert(ret_sender);
484 assert(ret_external);
485
486 p = object_path_startswith(path, prefix);
487 if (!p) {
488 *ret_sender = NULL;
489 *ret_external = NULL;
490 return 0;
491 }
492
493 q = strchr(p, '/');
494 if (!q) {
495 *ret_sender = NULL;
496 *ret_external = NULL;
497 return 0;
498 }
499
500 sender = bus_label_unescape_n(p, q - p);
501 external = bus_label_unescape(q + 1);
502 if (!sender || !external) {
503 free(sender);
504 free(external);
505 return -ENOMEM;
506 }
507
508 *ret_sender = sender;
509 *ret_external = external;
510 return 1;
511 }
512
513 int bus_track_add_name_many(sd_bus_track *t, char **l) {
514 int r = 0;
515
516 assert(t);
517
518 /* Continues adding after failure, and returns the first failure. */
519
520 STRV_FOREACH(i, l)
521 RET_GATHER(r, sd_bus_track_add_name(t, *i));
522 return r;
523 }
524
525 int bus_open_system_watch_bind_with_description(sd_bus **ret, const char *description) {
526 _cleanup_(sd_bus_close_unrefp) sd_bus *bus = NULL;
527 const char *e;
528 int r;
529
530 assert(ret);
531
532 /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal
533 * turned on. */
534
535 r = sd_bus_new(&bus);
536 if (r < 0)
537 return r;
538
539 if (description) {
540 r = sd_bus_set_description(bus, description);
541 if (r < 0)
542 return r;
543 }
544
545 e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
546 if (!e)
547 e = DEFAULT_SYSTEM_BUS_ADDRESS;
548
549 r = sd_bus_set_address(bus, e);
550 if (r < 0)
551 return r;
552
553 r = sd_bus_set_bus_client(bus, true);
554 if (r < 0)
555 return r;
556
557 r = sd_bus_negotiate_creds(bus, true, SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_EFFECTIVE_CAPS);
558 if (r < 0)
559 return r;
560
561 r = sd_bus_set_watch_bind(bus, true);
562 if (r < 0)
563 return r;
564
565 r = sd_bus_set_connected_signal(bus, true);
566 if (r < 0)
567 return r;
568
569 r = sd_bus_start(bus);
570 if (r < 0)
571 return r;
572
573 *ret = TAKE_PTR(bus);
574
575 return 0;
576 }
577
578 int bus_reply_pair_array(sd_bus_message *m, char **l) {
579 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
580 int r;
581
582 assert(m);
583
584 /* Reply to the specified message with a message containing a dictionary put together from the
585 * specified strv */
586
587 r = sd_bus_message_new_method_return(m, &reply);
588 if (r < 0)
589 return r;
590
591 r = sd_bus_message_open_container(reply, 'a', "{ss}");
592 if (r < 0)
593 return r;
594
595 STRV_FOREACH_PAIR(k, v, l) {
596 r = sd_bus_message_append(reply, "{ss}", *k, *v);
597 if (r < 0)
598 return r;
599 }
600
601 r = sd_bus_message_close_container(reply);
602 if (r < 0)
603 return r;
604
605 return sd_bus_send(NULL, reply, NULL);
606 }
607
608 static int method_dump_memory_state_by_fd(sd_bus_message *message, void *userdata, sd_bus_error *ret_error) {
609 _cleanup_(memstream_done) MemStream m = {};
610 _cleanup_free_ char *dump = NULL;
611 _cleanup_close_ int fd = -EBADF;
612 size_t dump_size;
613 FILE *f;
614 int r;
615
616 assert(message);
617
618 f = memstream_init(&m);
619 if (!f)
620 return -ENOMEM;
621
622 r = RET_NERRNO(malloc_info(/* options= */ 0, f));
623 if (r < 0)
624 return r;
625
626 r = memstream_finalize(&m, &dump, &dump_size);
627 if (r < 0)
628 return r;
629
630 fd = acquire_data_fd(dump, dump_size, 0);
631 if (fd < 0)
632 return fd;
633
634 r = sd_bus_reply_method_return(message, "h", fd);
635 if (r < 0)
636 return r;
637
638 return 1; /* Stop further processing */
639 }
640
641 /* The default install callback will fail and disconnect the bus if it cannot register the match, but this
642 * is only a debug method, we definitely don't want to fail in case there's some permission issue. */
643 static int dummy_install_callback(sd_bus_message *message, void *userdata, sd_bus_error *ret_error) {
644 return 1;
645 }
646
647 int bus_register_malloc_status(sd_bus *bus, const char *destination) {
648 const char *match;
649 int r;
650
651 assert(bus);
652 assert(!isempty(destination));
653
654 match = strjoina("type='method_call',"
655 "interface='org.freedesktop.MemoryAllocation1',"
656 "path='/org/freedesktop/MemoryAllocation1',"
657 "destination='", destination, "',",
658 "member='GetMallocInfo'");
659
660 r = sd_bus_add_match_async(bus, NULL, match, method_dump_memory_state_by_fd, dummy_install_callback, NULL);
661 if (r < 0)
662 return log_debug_errno(r, "Failed to subscribe to GetMallocInfo() calls on MemoryAllocation1 interface: %m");
663
664 return 0;
665 }
666
667 static void bus_message_unref_wrapper(void *m) {
668 sd_bus_message_unref(m);
669 }
670
671 const struct hash_ops bus_message_hash_ops = {
672 .hash = trivial_hash_func,
673 .compare = trivial_compare_func,
674 .free_value = bus_message_unref_wrapper,
675 };
676
677 int bus_message_append_string_set(sd_bus_message *m, Set *set) {
678 const char *s;
679 int r;
680
681 assert(m);
682
683 r = sd_bus_message_open_container(m, 'a', "s");
684 if (r < 0)
685 return r;
686
687 SET_FOREACH(s, set) {
688 r = sd_bus_message_append(m, "s", s);
689 if (r < 0)
690 return r;
691 }
692
693 return sd_bus_message_close_container(m);
694 }
695
696 int bus_property_get_string_set(
697 sd_bus *bus,
698 const char *path,
699 const char *interface,
700 const char *property,
701 sd_bus_message *reply,
702 void *userdata,
703 sd_bus_error *error) {
704
705 Set **s = ASSERT_PTR(userdata);
706
707 assert(bus);
708 assert(property);
709 assert(reply);
710
711 return bus_message_append_string_set(reply, *s);
712 }
713
714 int bus_creds_get_pidref(
715 sd_bus_creds *c,
716 PidRef *ret) {
717
718 int pidfd = -EBADF;
719 pid_t pid;
720 int r;
721
722 assert(c);
723 assert(ret);
724
725 r = sd_bus_creds_get_pid(c, &pid);
726 if (r < 0)
727 return r;
728
729 r = sd_bus_creds_get_pidfd_dup(c, &pidfd);
730 if (r < 0 && r != -ENODATA)
731 return r;
732
733 *ret = (PidRef) {
734 .pid = pid,
735 .fd = pidfd,
736 };
737
738 return 0;
739 }
740
741 int bus_query_sender_pidref(
742 sd_bus_message *m,
743 PidRef *ret) {
744
745 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
746 int r;
747
748 assert(m);
749 assert(ret);
750
751 r = sd_bus_query_sender_creds(m, SD_BUS_CREDS_PID|SD_BUS_CREDS_PIDFD, &creds);
752 if (r < 0)
753 return r;
754
755 return bus_creds_get_pidref(creds, ret);
756 }