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