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