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