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