]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/bus-util.c
tree-wide: fix typo in comments and NEWS
[thirdparty/systemd.git] / src / shared / bus-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2013 Lennart Poettering
6 ***/
7
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <inttypes.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <sys/ioctl.h>
15 #include <sys/resource.h>
16 #include <sys/socket.h>
17 #include <unistd.h>
18
19 #include "sd-bus-protocol.h"
20 #include "sd-bus.h"
21 #include "sd-daemon.h"
22 #include "sd-event.h"
23 #include "sd-id128.h"
24
25 #include "alloc-util.h"
26 #include "bus-internal.h"
27 #include "bus-label.h"
28 #include "bus-message.h"
29 #include "bus-util.h"
30 #include "cap-list.h"
31 #include "cgroup-util.h"
32 #include "def.h"
33 #include "escape.h"
34 #include "fd-util.h"
35 #include "missing.h"
36 #include "mount-util.h"
37 #include "nsflags.h"
38 #include "parse-util.h"
39 #include "proc-cmdline.h"
40 #include "rlimit-util.h"
41 #include "stdio-util.h"
42 #include "strv.h"
43 #include "user-util.h"
44
45 static int name_owner_change_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
46 sd_event *e = userdata;
47
48 assert(m);
49 assert(e);
50
51 sd_bus_close(sd_bus_message_get_bus(m));
52 sd_event_exit(e, 0);
53
54 return 1;
55 }
56
57 int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name) {
58 const char *match;
59 const char *unique;
60 int r;
61
62 assert(e);
63 assert(bus);
64 assert(name);
65
66 /* We unregister the name here and then wait for the
67 * NameOwnerChanged signal for this event to arrive before we
68 * quit. We do this in order to make sure that any queued
69 * requests are still processed before we really exit. */
70
71 r = sd_bus_get_unique_name(bus, &unique);
72 if (r < 0)
73 return r;
74
75 match = strjoina(
76 "sender='org.freedesktop.DBus',"
77 "type='signal',"
78 "interface='org.freedesktop.DBus',"
79 "member='NameOwnerChanged',"
80 "path='/org/freedesktop/DBus',"
81 "arg0='", name, "',",
82 "arg1='", unique, "',",
83 "arg2=''");
84
85 r = sd_bus_add_match_async(bus, NULL, match, name_owner_change_callback, NULL, e);
86 if (r < 0)
87 return r;
88
89 r = sd_bus_release_name_async(bus, NULL, name, NULL, NULL);
90 if (r < 0)
91 return r;
92
93 return 0;
94 }
95
96 int bus_event_loop_with_idle(
97 sd_event *e,
98 sd_bus *bus,
99 const char *name,
100 usec_t timeout,
101 check_idle_t check_idle,
102 void *userdata) {
103 bool exiting = false;
104 int r, code;
105
106 assert(e);
107 assert(bus);
108 assert(name);
109
110 for (;;) {
111 bool idle;
112
113 r = sd_event_get_state(e);
114 if (r < 0)
115 return r;
116 if (r == SD_EVENT_FINISHED)
117 break;
118
119 if (check_idle)
120 idle = check_idle(userdata);
121 else
122 idle = true;
123
124 r = sd_event_run(e, exiting || !idle ? (uint64_t) -1 : timeout);
125 if (r < 0)
126 return r;
127
128 if (r == 0 && !exiting && idle) {
129
130 r = sd_bus_try_close(bus);
131 if (r == -EBUSY)
132 continue;
133
134 /* Fallback for dbus1 connections: we
135 * unregister the name and wait for the
136 * response to come through for it */
137 if (r == -EOPNOTSUPP) {
138
139 /* Inform the service manager that we
140 * are going down, so that it will
141 * queue all further start requests,
142 * instead of assuming we are already
143 * running. */
144 sd_notify(false, "STOPPING=1");
145
146 r = bus_async_unregister_and_exit(e, bus, name);
147 if (r < 0)
148 return r;
149
150 exiting = true;
151 continue;
152 }
153
154 if (r < 0)
155 return r;
156
157 sd_event_exit(e, 0);
158 break;
159 }
160 }
161
162 r = sd_event_get_exit_code(e, &code);
163 if (r < 0)
164 return r;
165
166 return code;
167 }
168
169 int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error) {
170 _cleanup_(sd_bus_message_unrefp) sd_bus_message *rep = NULL;
171 int r, has_owner = 0;
172
173 assert(c);
174 assert(name);
175
176 r = sd_bus_call_method(c,
177 "org.freedesktop.DBus",
178 "/org/freedesktop/dbus",
179 "org.freedesktop.DBus",
180 "NameHasOwner",
181 error,
182 &rep,
183 "s",
184 name);
185 if (r < 0)
186 return r;
187
188 r = sd_bus_message_read_basic(rep, 'b', &has_owner);
189 if (r < 0)
190 return sd_bus_error_set_errno(error, r);
191
192 return has_owner;
193 }
194
195 static int check_good_user(sd_bus_message *m, uid_t good_user) {
196 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
197 uid_t sender_uid;
198 int r;
199
200 assert(m);
201
202 if (good_user == UID_INVALID)
203 return 0;
204
205 r = sd_bus_query_sender_creds(m, SD_BUS_CREDS_EUID, &creds);
206 if (r < 0)
207 return r;
208
209 /* Don't trust augmented credentials for authorization */
210 assert_return((sd_bus_creds_get_augmented_mask(creds) & SD_BUS_CREDS_EUID) == 0, -EPERM);
211
212 r = sd_bus_creds_get_euid(creds, &sender_uid);
213 if (r < 0)
214 return r;
215
216 return sender_uid == good_user;
217 }
218
219 int bus_test_polkit(
220 sd_bus_message *call,
221 int capability,
222 const char *action,
223 const char **details,
224 uid_t good_user,
225 bool *_challenge,
226 sd_bus_error *e) {
227
228 int r;
229
230 assert(call);
231 assert(action);
232
233 /* Tests non-interactively! */
234
235 r = check_good_user(call, good_user);
236 if (r != 0)
237 return r;
238
239 r = sd_bus_query_sender_privilege(call, capability);
240 if (r < 0)
241 return r;
242 else if (r > 0)
243 return 1;
244 #if ENABLE_POLKIT
245 else {
246 _cleanup_(sd_bus_message_unrefp) sd_bus_message *request = NULL;
247 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
248 int authorized = false, challenge = false;
249 const char *sender, **k, **v;
250
251 sender = sd_bus_message_get_sender(call);
252 if (!sender)
253 return -EBADMSG;
254
255 r = sd_bus_message_new_method_call(
256 call->bus,
257 &request,
258 "org.freedesktop.PolicyKit1",
259 "/org/freedesktop/PolicyKit1/Authority",
260 "org.freedesktop.PolicyKit1.Authority",
261 "CheckAuthorization");
262 if (r < 0)
263 return r;
264
265 r = sd_bus_message_append(
266 request,
267 "(sa{sv})s",
268 "system-bus-name", 1, "name", "s", sender,
269 action);
270 if (r < 0)
271 return r;
272
273 r = sd_bus_message_open_container(request, 'a', "{ss}");
274 if (r < 0)
275 return r;
276
277 STRV_FOREACH_PAIR(k, v, details) {
278 r = sd_bus_message_append(request, "{ss}", *k, *v);
279 if (r < 0)
280 return r;
281 }
282
283 r = sd_bus_message_close_container(request);
284 if (r < 0)
285 return r;
286
287 r = sd_bus_message_append(request, "us", 0, NULL);
288 if (r < 0)
289 return r;
290
291 r = sd_bus_call(call->bus, request, 0, e, &reply);
292 if (r < 0) {
293 /* Treat no PK available as access denied */
294 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN)) {
295 sd_bus_error_free(e);
296 return -EACCES;
297 }
298
299 return r;
300 }
301
302 r = sd_bus_message_enter_container(reply, 'r', "bba{ss}");
303 if (r < 0)
304 return r;
305
306 r = sd_bus_message_read(reply, "bb", &authorized, &challenge);
307 if (r < 0)
308 return r;
309
310 if (authorized)
311 return 1;
312
313 if (_challenge) {
314 *_challenge = challenge;
315 return 0;
316 }
317 }
318 #endif
319
320 return -EACCES;
321 }
322
323 #if ENABLE_POLKIT
324
325 typedef struct AsyncPolkitQuery {
326 sd_bus_message *request, *reply;
327 sd_bus_message_handler_t callback;
328 void *userdata;
329 sd_bus_slot *slot;
330 Hashmap *registry;
331 } AsyncPolkitQuery;
332
333 static void async_polkit_query_free(AsyncPolkitQuery *q) {
334
335 if (!q)
336 return;
337
338 sd_bus_slot_unref(q->slot);
339
340 if (q->registry && q->request)
341 hashmap_remove(q->registry, q->request);
342
343 sd_bus_message_unref(q->request);
344 sd_bus_message_unref(q->reply);
345
346 free(q);
347 }
348
349 static int async_polkit_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
350 _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
351 AsyncPolkitQuery *q = userdata;
352 int r;
353
354 assert(reply);
355 assert(q);
356
357 q->slot = sd_bus_slot_unref(q->slot);
358 q->reply = sd_bus_message_ref(reply);
359
360 r = sd_bus_message_rewind(q->request, true);
361 if (r < 0) {
362 r = sd_bus_reply_method_errno(q->request, r, NULL);
363 goto finish;
364 }
365
366 r = q->callback(q->request, q->userdata, &error_buffer);
367 r = bus_maybe_reply_error(q->request, r, &error_buffer);
368
369 finish:
370 async_polkit_query_free(q);
371
372 return r;
373 }
374
375 #endif
376
377 int bus_verify_polkit_async(
378 sd_bus_message *call,
379 int capability,
380 const char *action,
381 const char **details,
382 bool interactive,
383 uid_t good_user,
384 Hashmap **registry,
385 sd_bus_error *error) {
386
387 #if ENABLE_POLKIT
388 _cleanup_(sd_bus_message_unrefp) sd_bus_message *pk = NULL;
389 AsyncPolkitQuery *q;
390 const char *sender, **k, **v;
391 sd_bus_message_handler_t callback;
392 void *userdata;
393 int c;
394 #endif
395 int r;
396
397 assert(call);
398 assert(action);
399 assert(registry);
400
401 r = check_good_user(call, good_user);
402 if (r != 0)
403 return r;
404
405 #if ENABLE_POLKIT
406 q = hashmap_get(*registry, call);
407 if (q) {
408 int authorized, challenge;
409
410 /* This is the second invocation of this function, and
411 * there's already a response from polkit, let's
412 * process it */
413 assert(q->reply);
414
415 if (sd_bus_message_is_method_error(q->reply, NULL)) {
416 const sd_bus_error *e;
417
418 /* Copy error from polkit reply */
419 e = sd_bus_message_get_error(q->reply);
420 sd_bus_error_copy(error, e);
421
422 /* Treat no PK available as access denied */
423 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN))
424 return -EACCES;
425
426 return -sd_bus_error_get_errno(e);
427 }
428
429 r = sd_bus_message_enter_container(q->reply, 'r', "bba{ss}");
430 if (r >= 0)
431 r = sd_bus_message_read(q->reply, "bb", &authorized, &challenge);
432
433 if (r < 0)
434 return r;
435
436 if (authorized)
437 return 1;
438
439 if (challenge)
440 return sd_bus_error_set(error, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED, "Interactive authentication required.");
441
442 return -EACCES;
443 }
444 #endif
445
446 r = sd_bus_query_sender_privilege(call, capability);
447 if (r < 0)
448 return r;
449 else if (r > 0)
450 return 1;
451
452 #if ENABLE_POLKIT
453 if (sd_bus_get_current_message(call->bus) != call)
454 return -EINVAL;
455
456 callback = sd_bus_get_current_handler(call->bus);
457 if (!callback)
458 return -EINVAL;
459
460 userdata = sd_bus_get_current_userdata(call->bus);
461
462 sender = sd_bus_message_get_sender(call);
463 if (!sender)
464 return -EBADMSG;
465
466 c = sd_bus_message_get_allow_interactive_authorization(call);
467 if (c < 0)
468 return c;
469 if (c > 0)
470 interactive = true;
471
472 r = hashmap_ensure_allocated(registry, NULL);
473 if (r < 0)
474 return r;
475
476 r = sd_bus_message_new_method_call(
477 call->bus,
478 &pk,
479 "org.freedesktop.PolicyKit1",
480 "/org/freedesktop/PolicyKit1/Authority",
481 "org.freedesktop.PolicyKit1.Authority",
482 "CheckAuthorization");
483 if (r < 0)
484 return r;
485
486 r = sd_bus_message_append(
487 pk,
488 "(sa{sv})s",
489 "system-bus-name", 1, "name", "s", sender,
490 action);
491 if (r < 0)
492 return r;
493
494 r = sd_bus_message_open_container(pk, 'a', "{ss}");
495 if (r < 0)
496 return r;
497
498 STRV_FOREACH_PAIR(k, v, details) {
499 r = sd_bus_message_append(pk, "{ss}", *k, *v);
500 if (r < 0)
501 return r;
502 }
503
504 r = sd_bus_message_close_container(pk);
505 if (r < 0)
506 return r;
507
508 r = sd_bus_message_append(pk, "us", !!interactive, NULL);
509 if (r < 0)
510 return r;
511
512 q = new0(AsyncPolkitQuery, 1);
513 if (!q)
514 return -ENOMEM;
515
516 q->request = sd_bus_message_ref(call);
517 q->callback = callback;
518 q->userdata = userdata;
519
520 r = hashmap_put(*registry, call, q);
521 if (r < 0) {
522 async_polkit_query_free(q);
523 return r;
524 }
525
526 q->registry = *registry;
527
528 r = sd_bus_call_async(call->bus, &q->slot, pk, async_polkit_callback, q, 0);
529 if (r < 0) {
530 async_polkit_query_free(q);
531 return r;
532 }
533
534 return 0;
535 #endif
536
537 return -EACCES;
538 }
539
540 void bus_verify_polkit_async_registry_free(Hashmap *registry) {
541 #if ENABLE_POLKIT
542 hashmap_free_with_destructor(registry, async_polkit_query_free);
543 #endif
544 }
545
546 int bus_check_peercred(sd_bus *c) {
547 struct ucred ucred;
548 int fd, r;
549
550 assert(c);
551
552 fd = sd_bus_get_fd(c);
553 if (fd < 0)
554 return fd;
555
556 r = getpeercred(fd, &ucred);
557 if (r < 0)
558 return r;
559
560 if (ucred.uid != 0 && ucred.uid != geteuid())
561 return -EPERM;
562
563 return 1;
564 }
565
566 int bus_connect_system_systemd(sd_bus **_bus) {
567 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
568 int r;
569
570 assert(_bus);
571
572 if (geteuid() != 0)
573 return sd_bus_default_system(_bus);
574
575 /* If we are root then let's talk directly to the system
576 * instance, instead of going via the bus */
577
578 r = sd_bus_new(&bus);
579 if (r < 0)
580 return r;
581
582 r = sd_bus_set_address(bus, "unix:path=/run/systemd/private");
583 if (r < 0)
584 return r;
585
586 r = sd_bus_start(bus);
587 if (r < 0)
588 return sd_bus_default_system(_bus);
589
590 r = bus_check_peercred(bus);
591 if (r < 0)
592 return r;
593
594 *_bus = TAKE_PTR(bus);
595
596 return 0;
597 }
598
599 int bus_connect_user_systemd(sd_bus **_bus) {
600 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
601 _cleanup_free_ char *ee = NULL;
602 const char *e;
603 int r;
604
605 assert(_bus);
606
607 e = secure_getenv("XDG_RUNTIME_DIR");
608 if (!e)
609 return sd_bus_default_user(_bus);
610
611 ee = bus_address_escape(e);
612 if (!ee)
613 return -ENOMEM;
614
615 r = sd_bus_new(&bus);
616 if (r < 0)
617 return r;
618
619 bus->address = strjoin("unix:path=", ee, "/systemd/private");
620 if (!bus->address)
621 return -ENOMEM;
622
623 r = sd_bus_start(bus);
624 if (r < 0)
625 return sd_bus_default_user(_bus);
626
627 r = bus_check_peercred(bus);
628 if (r < 0)
629 return r;
630
631 *_bus = TAKE_PTR(bus);
632
633 return 0;
634 }
635
636 #define print_property(name, fmt, ...) \
637 do { \
638 if (value) \
639 printf(fmt "\n", __VA_ARGS__); \
640 else \
641 printf("%s=" fmt "\n", name, __VA_ARGS__); \
642 } while (0)
643
644 int bus_print_property(const char *name, sd_bus_message *m, bool value, bool all) {
645 char type;
646 const char *contents;
647 int r;
648
649 assert(name);
650 assert(m);
651
652 r = sd_bus_message_peek_type(m, &type, &contents);
653 if (r < 0)
654 return r;
655
656 switch (type) {
657
658 case SD_BUS_TYPE_STRING: {
659 const char *s;
660
661 r = sd_bus_message_read_basic(m, type, &s);
662 if (r < 0)
663 return r;
664
665 if (all || !isempty(s)) {
666 bool good;
667
668 /* This property has a single value, so we need to take
669 * care not to print a new line, everything else is OK. */
670 good = !strchr(s, '\n');
671 print_property(name, "%s", good ? s : "[unprintable]");
672 }
673
674 return 1;
675 }
676
677 case SD_BUS_TYPE_BOOLEAN: {
678 int b;
679
680 r = sd_bus_message_read_basic(m, type, &b);
681 if (r < 0)
682 return r;
683
684 print_property(name, "%s", yes_no(b));
685
686 return 1;
687 }
688
689 case SD_BUS_TYPE_UINT64: {
690 uint64_t u;
691
692 r = sd_bus_message_read_basic(m, type, &u);
693 if (r < 0)
694 return r;
695
696 /* Yes, heuristics! But we can change this check
697 * should it turn out to not be sufficient */
698
699 if (endswith(name, "Timestamp") || STR_IN_SET(name, "NextElapseUSecRealtime", "LastTriggerUSec")) {
700 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
701
702 t = format_timestamp(timestamp, sizeof(timestamp), u);
703 if (t || all)
704 print_property(name, "%s", strempty(t));
705
706 } else if (strstr(name, "USec")) {
707 char timespan[FORMAT_TIMESPAN_MAX];
708
709 print_property(name, "%s", format_timespan(timespan, sizeof(timespan), u, 0));
710 } else if (streq(name, "RestrictNamespaces")) {
711 _cleanup_free_ char *s = NULL;
712 const char *result;
713
714 if ((u & NAMESPACE_FLAGS_ALL) == 0)
715 result = "yes";
716 else if ((u & NAMESPACE_FLAGS_ALL) == NAMESPACE_FLAGS_ALL)
717 result = "no";
718 else {
719 r = namespace_flags_to_string(u, &s);
720 if (r < 0)
721 return r;
722
723 result = s;
724 }
725
726 print_property(name, "%s", result);
727
728 } else if (streq(name, "MountFlags")) {
729 const char *result;
730
731 result = mount_propagation_flags_to_string(u);
732 if (!result)
733 return -EINVAL;
734
735 print_property(name, "%s", result);
736
737 } else if (STR_IN_SET(name, "CapabilityBoundingSet", "AmbientCapabilities")) {
738 _cleanup_free_ char *s = NULL;
739
740 r = capability_set_to_string_alloc(u, &s);
741 if (r < 0)
742 return r;
743
744 print_property(name, "%s", s);
745
746 } else if ((STR_IN_SET(name, "CPUWeight", "StartupCPUWeight", "IOWeight", "StartupIOWeight") && u == CGROUP_WEIGHT_INVALID) ||
747 (STR_IN_SET(name, "CPUShares", "StartupCPUShares") && u == CGROUP_CPU_SHARES_INVALID) ||
748 (STR_IN_SET(name, "BlockIOWeight", "StartupBlockIOWeight") && u == CGROUP_BLKIO_WEIGHT_INVALID) ||
749 (STR_IN_SET(name, "MemoryCurrent", "TasksCurrent") && u == (uint64_t) -1) ||
750 (endswith(name, "NSec") && u == (uint64_t) -1))
751
752 print_property(name, "%s", "[not set]");
753
754 else if ((STR_IN_SET(name, "MemoryLow", "MemoryHigh", "MemoryMax", "MemorySwapMax", "MemoryLimit") && u == CGROUP_LIMIT_MAX) ||
755 (STR_IN_SET(name, "TasksMax", "DefaultTasksMax") && u == (uint64_t) -1) ||
756 (startswith(name, "Limit") && u == (uint64_t) -1) ||
757 (startswith(name, "DefaultLimit") && u == (uint64_t) -1))
758
759 print_property(name, "%s", "infinity");
760 else
761 print_property(name, "%"PRIu64, u);
762
763 return 1;
764 }
765
766 case SD_BUS_TYPE_INT64: {
767 int64_t i;
768
769 r = sd_bus_message_read_basic(m, type, &i);
770 if (r < 0)
771 return r;
772
773 print_property(name, "%"PRIi64, i);
774
775 return 1;
776 }
777
778 case SD_BUS_TYPE_UINT32: {
779 uint32_t u;
780
781 r = sd_bus_message_read_basic(m, type, &u);
782 if (r < 0)
783 return r;
784
785 if (strstr(name, "UMask") || strstr(name, "Mode"))
786 print_property(name, "%04o", u);
787 else if (streq(name, "UID")) {
788 if (u == UID_INVALID)
789 print_property(name, "%s", "[not set]");
790 else
791 print_property(name, "%"PRIu32, u);
792 } else if (streq(name, "GID")) {
793 if (u == GID_INVALID)
794 print_property(name, "%s", "[not set]");
795 else
796 print_property(name, "%"PRIu32, u);
797 } else
798 print_property(name, "%"PRIu32, u);
799
800 return 1;
801 }
802
803 case SD_BUS_TYPE_INT32: {
804 int32_t i;
805
806 r = sd_bus_message_read_basic(m, type, &i);
807 if (r < 0)
808 return r;
809
810 print_property(name, "%"PRIi32, i);
811 return 1;
812 }
813
814 case SD_BUS_TYPE_DOUBLE: {
815 double d;
816
817 r = sd_bus_message_read_basic(m, type, &d);
818 if (r < 0)
819 return r;
820
821 print_property(name, "%g", d);
822 return 1;
823 }
824
825 case SD_BUS_TYPE_ARRAY:
826 if (streq(contents, "s")) {
827 bool first = true;
828 const char *str;
829
830 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, contents);
831 if (r < 0)
832 return r;
833
834 while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &str)) > 0) {
835 bool good;
836
837 if (first && !value)
838 printf("%s=", name);
839
840 /* This property has multiple space-separated values, so
841 * neither spaces nor newlines can be allowed in a value. */
842 good = str[strcspn(str, " \n")] == '\0';
843
844 printf("%s%s", first ? "" : " ", good ? str : "[unprintable]");
845
846 first = false;
847 }
848 if (r < 0)
849 return r;
850
851 if (first && all && !value)
852 printf("%s=", name);
853 if (!first || all)
854 puts("");
855
856 r = sd_bus_message_exit_container(m);
857 if (r < 0)
858 return r;
859
860 return 1;
861
862 } else if (streq(contents, "y")) {
863 const uint8_t *u;
864 size_t n;
865
866 r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, (const void**) &u, &n);
867 if (r < 0)
868 return r;
869
870 if (all || n > 0) {
871 unsigned int i;
872
873 if (!value)
874 printf("%s=", name);
875
876 for (i = 0; i < n; i++)
877 printf("%02x", u[i]);
878
879 puts("");
880 }
881
882 return 1;
883
884 } else if (streq(contents, "u")) {
885 uint32_t *u;
886 size_t n;
887
888 r = sd_bus_message_read_array(m, SD_BUS_TYPE_UINT32, (const void**) &u, &n);
889 if (r < 0)
890 return r;
891
892 if (all || n > 0) {
893 unsigned int i;
894
895 if (!value)
896 printf("%s=", name);
897
898 for (i = 0; i < n; i++)
899 printf("%08x", u[i]);
900
901 puts("");
902 }
903
904 return 1;
905 }
906
907 break;
908 }
909
910 return 0;
911 }
912
913 int bus_message_print_all_properties(
914 sd_bus_message *m,
915 bus_message_print_t func,
916 char **filter,
917 bool value,
918 bool all,
919 Set **found_properties) {
920
921 int r;
922
923 assert(m);
924
925 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
926 if (r < 0)
927 return r;
928
929 while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
930 const char *name;
931 const char *contents;
932
933 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &name);
934 if (r < 0)
935 return r;
936
937 if (found_properties) {
938 r = set_ensure_allocated(found_properties, &string_hash_ops);
939 if (r < 0)
940 return log_oom();
941
942 r = set_put(*found_properties, name);
943 if (r < 0 && r != EEXIST)
944 return log_oom();
945 }
946
947 if (!filter || strv_find(filter, name)) {
948 r = sd_bus_message_peek_type(m, NULL, &contents);
949 if (r < 0)
950 return r;
951
952 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
953 if (r < 0)
954 return r;
955
956 if (func)
957 r = func(name, m, value, all);
958 if (!func || r == 0)
959 r = bus_print_property(name, m, value, all);
960 if (r < 0)
961 return r;
962 if (r == 0) {
963 if (all)
964 printf("%s=[unprintable]\n", name);
965 /* skip what we didn't read */
966 r = sd_bus_message_skip(m, contents);
967 if (r < 0)
968 return r;
969 }
970
971 r = sd_bus_message_exit_container(m);
972 if (r < 0)
973 return r;
974 } else {
975 r = sd_bus_message_skip(m, "v");
976 if (r < 0)
977 return r;
978 }
979
980 r = sd_bus_message_exit_container(m);
981 if (r < 0)
982 return r;
983 }
984 if (r < 0)
985 return r;
986
987 r = sd_bus_message_exit_container(m);
988 if (r < 0)
989 return r;
990
991 return 0;
992 }
993
994 int bus_print_all_properties(
995 sd_bus *bus,
996 const char *dest,
997 const char *path,
998 bus_message_print_t func,
999 char **filter,
1000 bool value,
1001 bool all,
1002 Set **found_properties) {
1003
1004 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1005 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1006 int r;
1007
1008 assert(bus);
1009 assert(path);
1010
1011 r = sd_bus_call_method(bus,
1012 dest,
1013 path,
1014 "org.freedesktop.DBus.Properties",
1015 "GetAll",
1016 &error,
1017 &reply,
1018 "s", "");
1019 if (r < 0)
1020 return r;
1021
1022 return bus_message_print_all_properties(reply, func, filter, value, all, found_properties);
1023 }
1024
1025 int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1026 sd_id128_t *p = userdata;
1027 const void *v;
1028 size_t n;
1029 int r;
1030
1031 r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n);
1032 if (r < 0)
1033 return r;
1034
1035 if (n == 0)
1036 *p = SD_ID128_NULL;
1037 else if (n == 16)
1038 memcpy((*p).bytes, v, n);
1039 else
1040 return -EINVAL;
1041
1042 return 0;
1043 }
1044
1045 static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, unsigned flags, sd_bus_error *error, void *userdata) {
1046 char type;
1047 int r;
1048
1049 r = sd_bus_message_peek_type(m, &type, NULL);
1050 if (r < 0)
1051 return r;
1052
1053 switch (type) {
1054
1055 case SD_BUS_TYPE_STRING: {
1056 const char **p = userdata;
1057 const char *s;
1058
1059 r = sd_bus_message_read_basic(m, type, &s);
1060 if (r < 0)
1061 return r;
1062
1063 if (isempty(s))
1064 s = NULL;
1065
1066 if (flags & BUS_MAP_STRDUP)
1067 return free_and_strdup((char **) userdata, s);
1068
1069 *p = s;
1070 return 0;
1071 }
1072
1073 case SD_BUS_TYPE_ARRAY: {
1074 _cleanup_strv_free_ char **l = NULL;
1075 char ***p = userdata;
1076
1077 r = bus_message_read_strv_extend(m, &l);
1078 if (r < 0)
1079 return r;
1080
1081 return strv_free_and_replace(*p, l);
1082 }
1083
1084 case SD_BUS_TYPE_BOOLEAN: {
1085 int b;
1086
1087 r = sd_bus_message_read_basic(m, type, &b);
1088 if (r < 0)
1089 return r;
1090
1091 if (flags & BUS_MAP_BOOLEAN_AS_BOOL)
1092 * (bool*) userdata = !!b;
1093 else
1094 * (int*) userdata = b;
1095
1096 return 0;
1097 }
1098
1099 case SD_BUS_TYPE_INT32:
1100 case SD_BUS_TYPE_UINT32: {
1101 uint32_t u, *p = userdata;
1102
1103 r = sd_bus_message_read_basic(m, type, &u);
1104 if (r < 0)
1105 return r;
1106
1107 *p = u;
1108 return 0;
1109 }
1110
1111 case SD_BUS_TYPE_INT64:
1112 case SD_BUS_TYPE_UINT64: {
1113 uint64_t t, *p = userdata;
1114
1115 r = sd_bus_message_read_basic(m, type, &t);
1116 if (r < 0)
1117 return r;
1118
1119 *p = t;
1120 return 0;
1121 }
1122
1123 case SD_BUS_TYPE_DOUBLE: {
1124 double d, *p = userdata;
1125
1126 r = sd_bus_message_read_basic(m, type, &d);
1127 if (r < 0)
1128 return r;
1129
1130 *p = d;
1131 return 0;
1132 }}
1133
1134 return -EOPNOTSUPP;
1135 }
1136
1137 int bus_message_map_all_properties(
1138 sd_bus_message *m,
1139 const struct bus_properties_map *map,
1140 unsigned flags,
1141 sd_bus_error *error,
1142 void *userdata) {
1143
1144 int r;
1145
1146 assert(m);
1147 assert(map);
1148
1149 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
1150 if (r < 0)
1151 return r;
1152
1153 while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1154 const struct bus_properties_map *prop;
1155 const char *member;
1156 const char *contents;
1157 void *v;
1158 unsigned i;
1159
1160 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
1161 if (r < 0)
1162 return r;
1163
1164 for (i = 0, prop = NULL; map[i].member; i++)
1165 if (streq(map[i].member, member)) {
1166 prop = &map[i];
1167 break;
1168 }
1169
1170 if (prop) {
1171 r = sd_bus_message_peek_type(m, NULL, &contents);
1172 if (r < 0)
1173 return r;
1174
1175 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
1176 if (r < 0)
1177 return r;
1178
1179 v = (uint8_t *)userdata + prop->offset;
1180 if (map[i].set)
1181 r = prop->set(sd_bus_message_get_bus(m), member, m, error, v);
1182 else
1183 r = map_basic(sd_bus_message_get_bus(m), member, m, flags, error, v);
1184 if (r < 0)
1185 return r;
1186
1187 r = sd_bus_message_exit_container(m);
1188 if (r < 0)
1189 return r;
1190 } else {
1191 r = sd_bus_message_skip(m, "v");
1192 if (r < 0)
1193 return r;
1194 }
1195
1196 r = sd_bus_message_exit_container(m);
1197 if (r < 0)
1198 return r;
1199 }
1200 if (r < 0)
1201 return r;
1202
1203 return sd_bus_message_exit_container(m);
1204 }
1205
1206 int bus_message_map_properties_changed(
1207 sd_bus_message *m,
1208 const struct bus_properties_map *map,
1209 unsigned flags,
1210 sd_bus_error *error,
1211 void *userdata) {
1212
1213 const char *member;
1214 int r, invalidated, i;
1215
1216 assert(m);
1217 assert(map);
1218
1219 r = bus_message_map_all_properties(m, map, flags, error, userdata);
1220 if (r < 0)
1221 return r;
1222
1223 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s");
1224 if (r < 0)
1225 return r;
1226
1227 invalidated = 0;
1228 while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0)
1229 for (i = 0; map[i].member; i++)
1230 if (streq(map[i].member, member)) {
1231 ++invalidated;
1232 break;
1233 }
1234 if (r < 0)
1235 return r;
1236
1237 r = sd_bus_message_exit_container(m);
1238 if (r < 0)
1239 return r;
1240
1241 return invalidated;
1242 }
1243
1244 int bus_map_all_properties(
1245 sd_bus *bus,
1246 const char *destination,
1247 const char *path,
1248 const struct bus_properties_map *map,
1249 unsigned flags,
1250 sd_bus_error *error,
1251 sd_bus_message **reply,
1252 void *userdata) {
1253
1254 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1255 int r;
1256
1257 assert(bus);
1258 assert(destination);
1259 assert(path);
1260 assert(map);
1261 assert(reply || (flags & BUS_MAP_STRDUP));
1262
1263 r = sd_bus_call_method(
1264 bus,
1265 destination,
1266 path,
1267 "org.freedesktop.DBus.Properties",
1268 "GetAll",
1269 error,
1270 &m,
1271 "s", "");
1272 if (r < 0)
1273 return r;
1274
1275 r = bus_message_map_all_properties(m, map, flags, error, userdata);
1276 if (r < 0)
1277 return r;
1278
1279 if (reply)
1280 *reply = sd_bus_message_ref(m);
1281
1282 return r;
1283 }
1284
1285 int bus_connect_transport(BusTransport transport, const char *host, bool user, sd_bus **ret) {
1286 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1287 int r;
1288
1289 assert(transport >= 0);
1290 assert(transport < _BUS_TRANSPORT_MAX);
1291 assert(ret);
1292
1293 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1294 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1295
1296 switch (transport) {
1297
1298 case BUS_TRANSPORT_LOCAL:
1299 if (user)
1300 r = sd_bus_default_user(&bus);
1301 else {
1302 if (sd_booted() <= 0) {
1303 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1304 log_error("System has not been booted with systemd as init system (PID 1). Can't operate.");
1305
1306 return -EHOSTDOWN;
1307 }
1308 r = sd_bus_default_system(&bus);
1309 }
1310 break;
1311
1312 case BUS_TRANSPORT_REMOTE:
1313 r = sd_bus_open_system_remote(&bus, host);
1314 break;
1315
1316 case BUS_TRANSPORT_MACHINE:
1317 r = sd_bus_open_system_machine(&bus, host);
1318 break;
1319
1320 default:
1321 assert_not_reached("Hmm, unknown transport type.");
1322 }
1323 if (r < 0)
1324 return r;
1325
1326 r = sd_bus_set_exit_on_disconnect(bus, true);
1327 if (r < 0)
1328 return r;
1329
1330 *ret = TAKE_PTR(bus);
1331
1332 return 0;
1333 }
1334
1335 int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1336 int r;
1337
1338 assert(transport >= 0);
1339 assert(transport < _BUS_TRANSPORT_MAX);
1340 assert(bus);
1341
1342 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1343 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1344
1345 switch (transport) {
1346
1347 case BUS_TRANSPORT_LOCAL:
1348 if (user)
1349 r = bus_connect_user_systemd(bus);
1350 else {
1351 if (sd_booted() <= 0) {
1352 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1353 log_error("System has not been booted with systemd as init system (PID 1). Can't operate.");
1354
1355 return -EHOSTDOWN;
1356 }
1357 r = bus_connect_system_systemd(bus);
1358 }
1359 break;
1360
1361 case BUS_TRANSPORT_REMOTE:
1362 r = sd_bus_open_system_remote(bus, host);
1363 break;
1364
1365 case BUS_TRANSPORT_MACHINE:
1366 r = sd_bus_open_system_machine(bus, host);
1367 break;
1368
1369 default:
1370 assert_not_reached("Hmm, unknown transport type.");
1371 }
1372
1373 return r;
1374 }
1375
1376 int bus_property_get_bool(
1377 sd_bus *bus,
1378 const char *path,
1379 const char *interface,
1380 const char *property,
1381 sd_bus_message *reply,
1382 void *userdata,
1383 sd_bus_error *error) {
1384
1385 int b = *(bool*) userdata;
1386
1387 return sd_bus_message_append_basic(reply, 'b', &b);
1388 }
1389
1390 int bus_property_set_bool(
1391 sd_bus *bus,
1392 const char *path,
1393 const char *interface,
1394 const char *property,
1395 sd_bus_message *value,
1396 void *userdata,
1397 sd_bus_error *error) {
1398
1399 int b, r;
1400
1401 r = sd_bus_message_read(value, "b", &b);
1402 if (r < 0)
1403 return r;
1404
1405 *(bool *) userdata = !!b;
1406 return 0;
1407 }
1408
1409 int bus_property_get_id128(
1410 sd_bus *bus,
1411 const char *path,
1412 const char *interface,
1413 const char *property,
1414 sd_bus_message *reply,
1415 void *userdata,
1416 sd_bus_error *error) {
1417
1418 sd_id128_t *id = userdata;
1419
1420 if (sd_id128_is_null(*id)) /* Add an empty array if the ID is zero */
1421 return sd_bus_message_append(reply, "ay", 0);
1422 else
1423 return sd_bus_message_append_array(reply, 'y', id->bytes, 16);
1424 }
1425
1426 #if __SIZEOF_SIZE_T__ != 8
1427 int bus_property_get_size(
1428 sd_bus *bus,
1429 const char *path,
1430 const char *interface,
1431 const char *property,
1432 sd_bus_message *reply,
1433 void *userdata,
1434 sd_bus_error *error) {
1435
1436 uint64_t sz = *(size_t*) userdata;
1437
1438 return sd_bus_message_append_basic(reply, 't', &sz);
1439 }
1440 #endif
1441
1442 #if __SIZEOF_LONG__ != 8
1443 int bus_property_get_long(
1444 sd_bus *bus,
1445 const char *path,
1446 const char *interface,
1447 const char *property,
1448 sd_bus_message *reply,
1449 void *userdata,
1450 sd_bus_error *error) {
1451
1452 int64_t l = *(long*) userdata;
1453
1454 return sd_bus_message_append_basic(reply, 'x', &l);
1455 }
1456
1457 int bus_property_get_ulong(
1458 sd_bus *bus,
1459 const char *path,
1460 const char *interface,
1461 const char *property,
1462 sd_bus_message *reply,
1463 void *userdata,
1464 sd_bus_error *error) {
1465
1466 uint64_t ul = *(unsigned long*) userdata;
1467
1468 return sd_bus_message_append_basic(reply, 't', &ul);
1469 }
1470 #endif
1471
1472 int bus_log_parse_error(int r) {
1473 return log_error_errno(r, "Failed to parse bus message: %m");
1474 }
1475
1476 int bus_log_create_error(int r) {
1477 return log_error_errno(r, "Failed to create bus message: %m");
1478 }
1479
1480 /**
1481 * bus_path_encode_unique() - encode unique object path
1482 * @b: bus connection or NULL
1483 * @prefix: object path prefix
1484 * @sender_id: unique-name of client, or NULL
1485 * @external_id: external ID to be chosen by client, or NULL
1486 * @ret_path: storage for encoded object path pointer
1487 *
1488 * Whenever we provide a bus API that allows clients to create and manage
1489 * server-side objects, we need to provide a unique name for these objects. If
1490 * we let the server choose the name, we suffer from a race condition: If a
1491 * client creates an object asynchronously, it cannot destroy that object until
1492 * it received the method reply. It cannot know the name of the new object,
1493 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
1494 *
1495 * Therefore, many APIs allow the client to choose the unique name for newly
1496 * created objects. There're two problems to solve, though:
1497 * 1) Object names are usually defined via dbus object paths, which are
1498 * usually globally namespaced. Therefore, multiple clients must be able
1499 * to choose unique object names without interference.
1500 * 2) If multiple libraries share the same bus connection, they must be
1501 * able to choose unique object names without interference.
1502 * The first problem is solved easily by prefixing a name with the
1503 * unique-bus-name of a connection. The server side must enforce this and
1504 * reject any other name. The second problem is solved by providing unique
1505 * suffixes from within sd-bus.
1506 *
1507 * This helper allows clients to create unique object-paths. It uses the
1508 * template '/prefix/sender_id/external_id' and returns the new path in
1509 * @ret_path (must be freed by the caller).
1510 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
1511 * NULL, this function allocates a unique suffix via @b (by requesting a new
1512 * cookie). If both @sender_id and @external_id are given, @b can be passed as
1513 * NULL.
1514 *
1515 * Returns: 0 on success, negative error code on failure.
1516 */
1517 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
1518 _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
1519 char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
1520 int r;
1521
1522 assert_return(b || (sender_id && external_id), -EINVAL);
1523 assert_return(object_path_is_valid(prefix), -EINVAL);
1524 assert_return(ret_path, -EINVAL);
1525
1526 if (!sender_id) {
1527 r = sd_bus_get_unique_name(b, &sender_id);
1528 if (r < 0)
1529 return r;
1530 }
1531
1532 if (!external_id) {
1533 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
1534 external_id = external_buf;
1535 }
1536
1537 sender_label = bus_label_escape(sender_id);
1538 if (!sender_label)
1539 return -ENOMEM;
1540
1541 external_label = bus_label_escape(external_id);
1542 if (!external_label)
1543 return -ENOMEM;
1544
1545 p = strjoin(prefix, "/", sender_label, "/", external_label);
1546 if (!p)
1547 return -ENOMEM;
1548
1549 *ret_path = p;
1550 return 0;
1551 }
1552
1553 /**
1554 * bus_path_decode_unique() - decode unique object path
1555 * @path: object path to decode
1556 * @prefix: object path prefix
1557 * @ret_sender: output parameter for sender-id label
1558 * @ret_external: output parameter for external-id label
1559 *
1560 * This does the reverse of bus_path_encode_unique() (see its description for
1561 * details). Both trailing labels, sender-id and external-id, are unescaped and
1562 * returned in the given output parameters (the caller must free them).
1563 *
1564 * Note that this function returns 0 if the path does not match the template
1565 * (see bus_path_encode_unique()), 1 if it matched.
1566 *
1567 * Returns: Negative error code on failure, 0 if the given object path does not
1568 * match the template (return parameters are set to NULL), 1 if it was
1569 * parsed successfully (return parameters contain allocated labels).
1570 */
1571 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
1572 const char *p, *q;
1573 char *sender, *external;
1574
1575 assert(object_path_is_valid(path));
1576 assert(object_path_is_valid(prefix));
1577 assert(ret_sender);
1578 assert(ret_external);
1579
1580 p = object_path_startswith(path, prefix);
1581 if (!p) {
1582 *ret_sender = NULL;
1583 *ret_external = NULL;
1584 return 0;
1585 }
1586
1587 q = strchr(p, '/');
1588 if (!q) {
1589 *ret_sender = NULL;
1590 *ret_external = NULL;
1591 return 0;
1592 }
1593
1594 sender = bus_label_unescape_n(p, q - p);
1595 external = bus_label_unescape(q + 1);
1596 if (!sender || !external) {
1597 free(sender);
1598 free(external);
1599 return -ENOMEM;
1600 }
1601
1602 *ret_sender = sender;
1603 *ret_external = external;
1604 return 1;
1605 }
1606
1607 int bus_property_get_rlimit(
1608 sd_bus *bus,
1609 const char *path,
1610 const char *interface,
1611 const char *property,
1612 sd_bus_message *reply,
1613 void *userdata,
1614 sd_bus_error *error) {
1615
1616 const char *is_soft;
1617 struct rlimit *rl;
1618 uint64_t u;
1619 rlim_t x;
1620
1621 assert(bus);
1622 assert(reply);
1623 assert(userdata);
1624
1625 is_soft = endswith(property, "Soft");
1626
1627 rl = *(struct rlimit**) userdata;
1628 if (rl)
1629 x = is_soft ? rl->rlim_cur : rl->rlim_max;
1630 else {
1631 struct rlimit buf = {};
1632 const char *s, *p;
1633 int z;
1634
1635 /* Chop off "Soft" suffix */
1636 s = is_soft ? strndupa(property, is_soft - property) : property;
1637
1638 /* Skip over any prefix, such as "Default" */
1639 assert_se(p = strstr(s, "Limit"));
1640
1641 z = rlimit_from_string(p + 5);
1642 assert(z >= 0);
1643
1644 (void) getrlimit(z, &buf);
1645 x = is_soft ? buf.rlim_cur : buf.rlim_max;
1646 }
1647
1648 /* rlim_t might have different sizes, let's map RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on all
1649 * archs */
1650 u = x == RLIM_INFINITY ? (uint64_t) -1 : (uint64_t) x;
1651
1652 return sd_bus_message_append(reply, "t", u);
1653 }
1654
1655 int bus_track_add_name_many(sd_bus_track *t, char **l) {
1656 int r = 0;
1657 char **i;
1658
1659 assert(t);
1660
1661 /* Continues adding after failure, and returns the first failure. */
1662
1663 STRV_FOREACH(i, l) {
1664 int k;
1665
1666 k = sd_bus_track_add_name(t, *i);
1667 if (k < 0 && r >= 0)
1668 r = k;
1669 }
1670
1671 return r;
1672 }
1673
1674 int bus_open_system_watch_bind_with_description(sd_bus **ret, const char *description) {
1675 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1676 const char *e;
1677 int r;
1678
1679 assert(ret);
1680
1681 /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal turned on. */
1682
1683 r = sd_bus_new(&bus);
1684 if (r < 0)
1685 return r;
1686
1687 if (description) {
1688 r = sd_bus_set_description(bus, description);
1689 if (r < 0)
1690 return r;
1691 }
1692
1693 e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1694 if (!e)
1695 e = DEFAULT_SYSTEM_BUS_ADDRESS;
1696
1697 r = sd_bus_set_address(bus, e);
1698 if (r < 0)
1699 return r;
1700
1701 r = sd_bus_set_bus_client(bus, true);
1702 if (r < 0)
1703 return r;
1704
1705 r = sd_bus_set_trusted(bus, true);
1706 if (r < 0)
1707 return r;
1708
1709 r = sd_bus_negotiate_creds(bus, true, SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_EFFECTIVE_CAPS);
1710 if (r < 0)
1711 return r;
1712
1713 r = sd_bus_set_watch_bind(bus, true);
1714 if (r < 0)
1715 return r;
1716
1717 r = sd_bus_set_connected_signal(bus, true);
1718 if (r < 0)
1719 return r;
1720
1721 r = sd_bus_start(bus);
1722 if (r < 0)
1723 return r;
1724
1725 *ret = TAKE_PTR(bus);
1726
1727 return 0;
1728 }
1729
1730 struct request_name_data {
1731 const char *name;
1732 uint64_t flags;
1733 void *userdata;
1734 };
1735
1736 static int reload_dbus_handler(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1737 _cleanup_free_ struct request_name_data *data = userdata;
1738 const sd_bus_error *e;
1739 int r;
1740
1741 assert(m);
1742 assert(data);
1743 assert(data->name);
1744
1745 e = sd_bus_message_get_error(m);
1746 if (e) {
1747 log_error_errno(sd_bus_error_get_errno(e), "Failed to reload DBus configuration: %s", e->message);
1748 return 1;
1749 }
1750
1751 /* Here, use the default request name handler to avoid an infinite loop of reloading and requesting. */
1752 r = sd_bus_request_name_async(sd_bus_message_get_bus(m), NULL, data->name, data->flags, NULL, data->userdata);
1753 if (r < 0)
1754 log_error_errno(r, "Failed to request name: %m");
1755
1756 return 1;
1757 }
1758
1759 static int request_name_handler_may_reload_dbus(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1760 _cleanup_free_ struct request_name_data *data = userdata;
1761 uint32_t ret;
1762 int r;
1763
1764 assert(m);
1765 assert(userdata);
1766
1767 if (sd_bus_message_is_method_error(m, NULL)) {
1768 const sd_bus_error *e = sd_bus_message_get_error(m);
1769
1770 if (!sd_bus_error_has_name(e, SD_BUS_ERROR_ACCESS_DENIED)) {
1771 log_debug_errno(sd_bus_error_get_errno(e),
1772 "Unable to request name, failing connection: %s",
1773 e->message);
1774
1775 bus_enter_closing(sd_bus_message_get_bus(m));
1776 return 1;
1777 }
1778
1779 log_debug_errno(sd_bus_error_get_errno(e),
1780 "Unable to request name, retry after reloading DBus configuration: %s",
1781 e->message);
1782
1783 /* If systemd-timesyncd.service enables DynamicUser= and dbus.service
1784 * started before the dynamic user is realized, then the DBus policy
1785 * about timesyncd has not been enabled yet. So, let's try to reload
1786 * DBus configuration, and after that request name again. Note that it
1787 * seems that no privileges are necessary to call the following method. */
1788
1789 r = sd_bus_call_method_async(
1790 sd_bus_message_get_bus(m),
1791 NULL,
1792 "org.freedesktop.DBus",
1793 "/org/freedesktop/DBus",
1794 "org.freedesktop.DBus",
1795 "ReloadConfig",
1796 reload_dbus_handler,
1797 userdata, NULL);
1798 if (r < 0) {
1799 log_error_errno(r, "Failed to reload DBus configuration: %m");
1800 bus_enter_closing(sd_bus_message_get_bus(m));
1801 return 1;
1802 }
1803
1804 data = NULL; /* Avoid free() */
1805 return 1;
1806 }
1807
1808 r = sd_bus_message_read(m, "u", &ret);
1809 if (r < 0)
1810 return r;
1811
1812 switch (ret) {
1813
1814 case BUS_NAME_ALREADY_OWNER:
1815 log_debug("Already owner of requested service name, ignoring.");
1816 return 1;
1817
1818 case BUS_NAME_IN_QUEUE:
1819 log_debug("In queue for requested service name.");
1820 return 1;
1821
1822 case BUS_NAME_PRIMARY_OWNER:
1823 log_debug("Successfully acquired requested service name.");
1824 return 1;
1825
1826 case BUS_NAME_EXISTS:
1827 log_debug("Requested service name already owned, failing connection.");
1828 bus_enter_closing(sd_bus_message_get_bus(m));
1829 return 1;
1830 }
1831
1832 log_debug("Unexpected response from RequestName(), failing connection.");
1833 bus_enter_closing(sd_bus_message_get_bus(m));
1834 return 1;
1835 }
1836
1837 int bus_request_name_async_may_reload_dbus(sd_bus *bus, sd_bus_slot **ret_slot, const char *name, uint64_t flags, void *userdata) {
1838 struct request_name_data *data;
1839
1840 data = new0(struct request_name_data, 1);
1841 if (!data)
1842 return -ENOMEM;
1843
1844 data->name = name;
1845 data->flags = flags;
1846 data->userdata = userdata;
1847
1848 return sd_bus_request_name_async(bus, ret_slot, name, flags, request_name_handler_may_reload_dbus, data);
1849 }
1850
1851 int bus_reply_pair_array(sd_bus_message *m, char **l) {
1852 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1853 char **k, **v;
1854 int r;
1855
1856 assert(m);
1857
1858 /* Reply to the specified message with a message containing a dictionary put together from the specified
1859 * strv */
1860
1861 r = sd_bus_message_new_method_return(m, &reply);
1862 if (r < 0)
1863 return r;
1864
1865 r = sd_bus_message_open_container(reply, 'a', "{ss}");
1866 if (r < 0)
1867 return r;
1868
1869 STRV_FOREACH_PAIR(k, v, l) {
1870 r = sd_bus_message_append(reply, "{ss}", *k, *v);
1871 if (r < 0)
1872 return r;
1873 }
1874
1875 r = sd_bus_message_close_container(reply);
1876 if (r < 0)
1877 return r;
1878
1879 return sd_bus_send(NULL, reply, NULL);
1880 }