]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/bus-util.c
Merge pull request #2970 from msekletar/machine-id-prefix-roota
[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 "cgroup-util.h"
43 #include "def.h"
44 #include "env-util.h"
45 #include "escape.h"
46 #include "extract-word.h"
47 #include "fd-util.h"
48 #include "hashmap.h"
49 #include "install.h"
50 #include "kdbus.h"
51 #include "log.h"
52 #include "macro.h"
53 #include "missing.h"
54 #include "parse-util.h"
55 #include "path-util.h"
56 #include "proc-cmdline.h"
57 #include "process-util.h"
58 #include "rlimit-util.h"
59 #include "set.h"
60 #include "signal-util.h"
61 #include "stdio-util.h"
62 #include "string-util.h"
63 #include "strv.h"
64 #include "syslog-util.h"
65 #include "time-util.h"
66 #include "unit-name.h"
67 #include "user-util.h"
68 #include "utf8.h"
69 #include "util.h"
70
71 static int name_owner_change_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
72 sd_event *e = userdata;
73
74 assert(m);
75 assert(e);
76
77 sd_bus_close(sd_bus_message_get_bus(m));
78 sd_event_exit(e, 0);
79
80 return 1;
81 }
82
83 int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name) {
84 _cleanup_free_ char *match = NULL;
85 const char *unique;
86 int r;
87
88 assert(e);
89 assert(bus);
90 assert(name);
91
92 /* We unregister the name here and then wait for the
93 * NameOwnerChanged signal for this event to arrive before we
94 * quit. We do this in order to make sure that any queued
95 * requests are still processed before we really exit. */
96
97 r = sd_bus_get_unique_name(bus, &unique);
98 if (r < 0)
99 return r;
100
101 r = asprintf(&match,
102 "sender='org.freedesktop.DBus',"
103 "type='signal',"
104 "interface='org.freedesktop.DBus',"
105 "member='NameOwnerChanged',"
106 "path='/org/freedesktop/DBus',"
107 "arg0='%s',"
108 "arg1='%s',"
109 "arg2=''", name, unique);
110 if (r < 0)
111 return -ENOMEM;
112
113 r = sd_bus_add_match(bus, NULL, match, name_owner_change_callback, e);
114 if (r < 0)
115 return r;
116
117 r = sd_bus_release_name(bus, name);
118 if (r < 0)
119 return r;
120
121 return 0;
122 }
123
124 int bus_event_loop_with_idle(
125 sd_event *e,
126 sd_bus *bus,
127 const char *name,
128 usec_t timeout,
129 check_idle_t check_idle,
130 void *userdata) {
131 bool exiting = false;
132 int r, code;
133
134 assert(e);
135 assert(bus);
136 assert(name);
137
138 for (;;) {
139 bool idle;
140
141 r = sd_event_get_state(e);
142 if (r < 0)
143 return r;
144 if (r == SD_EVENT_FINISHED)
145 break;
146
147 if (check_idle)
148 idle = check_idle(userdata);
149 else
150 idle = true;
151
152 r = sd_event_run(e, exiting || !idle ? (uint64_t) -1 : timeout);
153 if (r < 0)
154 return r;
155
156 if (r == 0 && !exiting && idle) {
157
158 r = sd_bus_try_close(bus);
159 if (r == -EBUSY)
160 continue;
161
162 /* Fallback for dbus1 connections: we
163 * unregister the name and wait for the
164 * response to come through for it */
165 if (r == -EOPNOTSUPP) {
166
167 /* Inform the service manager that we
168 * are going down, so that it will
169 * queue all further start requests,
170 * instead of assuming we are already
171 * running. */
172 sd_notify(false, "STOPPING=1");
173
174 r = bus_async_unregister_and_exit(e, bus, name);
175 if (r < 0)
176 return r;
177
178 exiting = true;
179 continue;
180 }
181
182 if (r < 0)
183 return r;
184
185 sd_event_exit(e, 0);
186 break;
187 }
188 }
189
190 r = sd_event_get_exit_code(e, &code);
191 if (r < 0)
192 return r;
193
194 return code;
195 }
196
197 int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error) {
198 _cleanup_(sd_bus_message_unrefp) sd_bus_message *rep = NULL;
199 int r, has_owner = 0;
200
201 assert(c);
202 assert(name);
203
204 r = sd_bus_call_method(c,
205 "org.freedesktop.DBus",
206 "/org/freedesktop/dbus",
207 "org.freedesktop.DBus",
208 "NameHasOwner",
209 error,
210 &rep,
211 "s",
212 name);
213 if (r < 0)
214 return r;
215
216 r = sd_bus_message_read_basic(rep, 'b', &has_owner);
217 if (r < 0)
218 return sd_bus_error_set_errno(error, r);
219
220 return has_owner;
221 }
222
223 static int check_good_user(sd_bus_message *m, uid_t good_user) {
224 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
225 uid_t sender_uid;
226 int r;
227
228 assert(m);
229
230 if (good_user == UID_INVALID)
231 return 0;
232
233 r = sd_bus_query_sender_creds(m, SD_BUS_CREDS_EUID, &creds);
234 if (r < 0)
235 return r;
236
237 /* Don't trust augmented credentials for authorization */
238 assert_return((sd_bus_creds_get_augmented_mask(creds) & SD_BUS_CREDS_EUID) == 0, -EPERM);
239
240 r = sd_bus_creds_get_euid(creds, &sender_uid);
241 if (r < 0)
242 return r;
243
244 return sender_uid == good_user;
245 }
246
247 int bus_test_polkit(
248 sd_bus_message *call,
249 int capability,
250 const char *action,
251 const char **details,
252 uid_t good_user,
253 bool *_challenge,
254 sd_bus_error *e) {
255
256 int r;
257
258 assert(call);
259 assert(action);
260
261 /* Tests non-interactively! */
262
263 r = check_good_user(call, good_user);
264 if (r != 0)
265 return r;
266
267 r = sd_bus_query_sender_privilege(call, capability);
268 if (r < 0)
269 return r;
270 else if (r > 0)
271 return 1;
272 #ifdef ENABLE_POLKIT
273 else {
274 _cleanup_(sd_bus_message_unrefp) sd_bus_message *request = NULL;
275 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
276 int authorized = false, challenge = false;
277 const char *sender, **k, **v;
278
279 sender = sd_bus_message_get_sender(call);
280 if (!sender)
281 return -EBADMSG;
282
283 r = sd_bus_message_new_method_call(
284 call->bus,
285 &request,
286 "org.freedesktop.PolicyKit1",
287 "/org/freedesktop/PolicyKit1/Authority",
288 "org.freedesktop.PolicyKit1.Authority",
289 "CheckAuthorization");
290 if (r < 0)
291 return r;
292
293 r = sd_bus_message_append(
294 request,
295 "(sa{sv})s",
296 "system-bus-name", 1, "name", "s", sender,
297 action);
298 if (r < 0)
299 return r;
300
301 r = sd_bus_message_open_container(request, 'a', "{ss}");
302 if (r < 0)
303 return r;
304
305 STRV_FOREACH_PAIR(k, v, details) {
306 r = sd_bus_message_append(request, "{ss}", *k, *v);
307 if (r < 0)
308 return r;
309 }
310
311 r = sd_bus_message_close_container(request);
312 if (r < 0)
313 return r;
314
315 r = sd_bus_message_append(request, "us", 0, NULL);
316 if (r < 0)
317 return r;
318
319 r = sd_bus_call(call->bus, request, 0, e, &reply);
320 if (r < 0) {
321 /* Treat no PK available as access denied */
322 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN)) {
323 sd_bus_error_free(e);
324 return -EACCES;
325 }
326
327 return r;
328 }
329
330 r = sd_bus_message_enter_container(reply, 'r', "bba{ss}");
331 if (r < 0)
332 return r;
333
334 r = sd_bus_message_read(reply, "bb", &authorized, &challenge);
335 if (r < 0)
336 return r;
337
338 if (authorized)
339 return 1;
340
341 if (_challenge) {
342 *_challenge = challenge;
343 return 0;
344 }
345 }
346 #endif
347
348 return -EACCES;
349 }
350
351 #ifdef ENABLE_POLKIT
352
353 typedef struct AsyncPolkitQuery {
354 sd_bus_message *request, *reply;
355 sd_bus_message_handler_t callback;
356 void *userdata;
357 sd_bus_slot *slot;
358 Hashmap *registry;
359 } AsyncPolkitQuery;
360
361 static void async_polkit_query_free(AsyncPolkitQuery *q) {
362
363 if (!q)
364 return;
365
366 sd_bus_slot_unref(q->slot);
367
368 if (q->registry && q->request)
369 hashmap_remove(q->registry, q->request);
370
371 sd_bus_message_unref(q->request);
372 sd_bus_message_unref(q->reply);
373
374 free(q);
375 }
376
377 static int async_polkit_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
378 _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
379 AsyncPolkitQuery *q = userdata;
380 int r;
381
382 assert(reply);
383 assert(q);
384
385 q->slot = sd_bus_slot_unref(q->slot);
386 q->reply = sd_bus_message_ref(reply);
387
388 r = sd_bus_message_rewind(q->request, true);
389 if (r < 0) {
390 r = sd_bus_reply_method_errno(q->request, r, NULL);
391 goto finish;
392 }
393
394 r = q->callback(q->request, q->userdata, &error_buffer);
395 r = bus_maybe_reply_error(q->request, r, &error_buffer);
396
397 finish:
398 async_polkit_query_free(q);
399
400 return r;
401 }
402
403 #endif
404
405 int bus_verify_polkit_async(
406 sd_bus_message *call,
407 int capability,
408 const char *action,
409 const char **details,
410 bool interactive,
411 uid_t good_user,
412 Hashmap **registry,
413 sd_bus_error *error) {
414
415 #ifdef ENABLE_POLKIT
416 _cleanup_(sd_bus_message_unrefp) sd_bus_message *pk = NULL;
417 AsyncPolkitQuery *q;
418 const char *sender, **k, **v;
419 sd_bus_message_handler_t callback;
420 void *userdata;
421 int c;
422 #endif
423 int r;
424
425 assert(call);
426 assert(action);
427 assert(registry);
428
429 r = check_good_user(call, good_user);
430 if (r != 0)
431 return r;
432
433 #ifdef ENABLE_POLKIT
434 q = hashmap_get(*registry, call);
435 if (q) {
436 int authorized, challenge;
437
438 /* This is the second invocation of this function, and
439 * there's already a response from polkit, let's
440 * process it */
441 assert(q->reply);
442
443 if (sd_bus_message_is_method_error(q->reply, NULL)) {
444 const sd_bus_error *e;
445
446 /* Copy error from polkit reply */
447 e = sd_bus_message_get_error(q->reply);
448 sd_bus_error_copy(error, e);
449
450 /* Treat no PK available as access denied */
451 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN))
452 return -EACCES;
453
454 return -sd_bus_error_get_errno(e);
455 }
456
457 r = sd_bus_message_enter_container(q->reply, 'r', "bba{ss}");
458 if (r >= 0)
459 r = sd_bus_message_read(q->reply, "bb", &authorized, &challenge);
460
461 if (r < 0)
462 return r;
463
464 if (authorized)
465 return 1;
466
467 if (challenge)
468 return sd_bus_error_set(error, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED, "Interactive authentication required.");
469
470 return -EACCES;
471 }
472 #endif
473
474 r = sd_bus_query_sender_privilege(call, capability);
475 if (r < 0)
476 return r;
477 else if (r > 0)
478 return 1;
479
480 #ifdef ENABLE_POLKIT
481 if (sd_bus_get_current_message(call->bus) != call)
482 return -EINVAL;
483
484 callback = sd_bus_get_current_handler(call->bus);
485 if (!callback)
486 return -EINVAL;
487
488 userdata = sd_bus_get_current_userdata(call->bus);
489
490 sender = sd_bus_message_get_sender(call);
491 if (!sender)
492 return -EBADMSG;
493
494 c = sd_bus_message_get_allow_interactive_authorization(call);
495 if (c < 0)
496 return c;
497 if (c > 0)
498 interactive = true;
499
500 r = hashmap_ensure_allocated(registry, NULL);
501 if (r < 0)
502 return r;
503
504 r = sd_bus_message_new_method_call(
505 call->bus,
506 &pk,
507 "org.freedesktop.PolicyKit1",
508 "/org/freedesktop/PolicyKit1/Authority",
509 "org.freedesktop.PolicyKit1.Authority",
510 "CheckAuthorization");
511 if (r < 0)
512 return r;
513
514 r = sd_bus_message_append(
515 pk,
516 "(sa{sv})s",
517 "system-bus-name", 1, "name", "s", sender,
518 action);
519 if (r < 0)
520 return r;
521
522 r = sd_bus_message_open_container(pk, 'a', "{ss}");
523 if (r < 0)
524 return r;
525
526 STRV_FOREACH_PAIR(k, v, details) {
527 r = sd_bus_message_append(pk, "{ss}", *k, *v);
528 if (r < 0)
529 return r;
530 }
531
532 r = sd_bus_message_close_container(pk);
533 if (r < 0)
534 return r;
535
536 r = sd_bus_message_append(pk, "us", !!interactive, NULL);
537 if (r < 0)
538 return r;
539
540 q = new0(AsyncPolkitQuery, 1);
541 if (!q)
542 return -ENOMEM;
543
544 q->request = sd_bus_message_ref(call);
545 q->callback = callback;
546 q->userdata = userdata;
547
548 r = hashmap_put(*registry, call, q);
549 if (r < 0) {
550 async_polkit_query_free(q);
551 return r;
552 }
553
554 q->registry = *registry;
555
556 r = sd_bus_call_async(call->bus, &q->slot, pk, async_polkit_callback, q, 0);
557 if (r < 0) {
558 async_polkit_query_free(q);
559 return r;
560 }
561
562 return 0;
563 #endif
564
565 return -EACCES;
566 }
567
568 void bus_verify_polkit_async_registry_free(Hashmap *registry) {
569 #ifdef ENABLE_POLKIT
570 AsyncPolkitQuery *q;
571
572 while ((q = hashmap_steal_first(registry)))
573 async_polkit_query_free(q);
574
575 hashmap_free(registry);
576 #endif
577 }
578
579 int bus_check_peercred(sd_bus *c) {
580 struct ucred ucred;
581 socklen_t l;
582 int fd;
583
584 assert(c);
585
586 fd = sd_bus_get_fd(c);
587 if (fd < 0)
588 return fd;
589
590 l = sizeof(struct ucred);
591 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
592 return -errno;
593
594 if (l != sizeof(struct ucred))
595 return -E2BIG;
596
597 if (ucred.uid != 0 && ucred.uid != geteuid())
598 return -EPERM;
599
600 return 1;
601 }
602
603 int bus_connect_system_systemd(sd_bus **_bus) {
604 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
605 int r;
606
607 assert(_bus);
608
609 if (geteuid() != 0)
610 return sd_bus_default_system(_bus);
611
612 /* If we are root and kdbus is not available, then let's talk
613 * directly to the system instance, instead of going via the
614 * bus */
615
616 r = sd_bus_new(&bus);
617 if (r < 0)
618 return r;
619
620 r = sd_bus_set_address(bus, KERNEL_SYSTEM_BUS_ADDRESS);
621 if (r < 0)
622 return r;
623
624 bus->bus_client = true;
625
626 r = sd_bus_start(bus);
627 if (r >= 0) {
628 *_bus = bus;
629 bus = NULL;
630 return 0;
631 }
632
633 bus = sd_bus_unref(bus);
634
635 r = sd_bus_new(&bus);
636 if (r < 0)
637 return r;
638
639 r = sd_bus_set_address(bus, "unix:path=/run/systemd/private");
640 if (r < 0)
641 return r;
642
643 r = sd_bus_start(bus);
644 if (r < 0)
645 return sd_bus_default_system(_bus);
646
647 r = bus_check_peercred(bus);
648 if (r < 0)
649 return r;
650
651 *_bus = bus;
652 bus = NULL;
653
654 return 0;
655 }
656
657 int bus_connect_user_systemd(sd_bus **_bus) {
658 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
659 _cleanup_free_ char *ee = NULL;
660 const char *e;
661 int r;
662
663 /* Try via kdbus first, and then directly */
664
665 assert(_bus);
666
667 r = sd_bus_new(&bus);
668 if (r < 0)
669 return r;
670
671 if (asprintf(&bus->address, KERNEL_USER_BUS_ADDRESS_FMT, getuid()) < 0)
672 return -ENOMEM;
673
674 bus->bus_client = true;
675
676 r = sd_bus_start(bus);
677 if (r >= 0) {
678 *_bus = bus;
679 bus = NULL;
680 return 0;
681 }
682
683 bus = sd_bus_unref(bus);
684
685 e = secure_getenv("XDG_RUNTIME_DIR");
686 if (!e)
687 return sd_bus_default_user(_bus);
688
689 ee = bus_address_escape(e);
690 if (!ee)
691 return -ENOMEM;
692
693 r = sd_bus_new(&bus);
694 if (r < 0)
695 return r;
696
697 bus->address = strjoin("unix:path=", ee, "/systemd/private", NULL);
698 if (!bus->address)
699 return -ENOMEM;
700
701 r = sd_bus_start(bus);
702 if (r < 0)
703 return sd_bus_default_user(_bus);
704
705 r = bus_check_peercred(bus);
706 if (r < 0)
707 return r;
708
709 *_bus = bus;
710 bus = NULL;
711
712 return 0;
713 }
714
715 #define print_property(name, fmt, ...) \
716 do { \
717 if (value) \
718 printf(fmt "\n", __VA_ARGS__); \
719 else \
720 printf("%s=" fmt "\n", name, __VA_ARGS__); \
721 } while(0)
722
723 int bus_print_property(const char *name, sd_bus_message *property, bool value, bool all) {
724 char type;
725 const char *contents;
726 int r;
727
728 assert(name);
729 assert(property);
730
731 r = sd_bus_message_peek_type(property, &type, &contents);
732 if (r < 0)
733 return r;
734
735 switch (type) {
736
737 case SD_BUS_TYPE_STRING: {
738 const char *s;
739
740 r = sd_bus_message_read_basic(property, type, &s);
741 if (r < 0)
742 return r;
743
744 if (all || !isempty(s)) {
745 _cleanup_free_ char *escaped = NULL;
746
747 escaped = xescape(s, "\n");
748 if (!escaped)
749 return -ENOMEM;
750
751 print_property(name, "%s", escaped);
752 }
753
754 return 1;
755 }
756
757 case SD_BUS_TYPE_BOOLEAN: {
758 int b;
759
760 r = sd_bus_message_read_basic(property, type, &b);
761 if (r < 0)
762 return r;
763
764 print_property(name, "%s", yes_no(b));
765
766 return 1;
767 }
768
769 case SD_BUS_TYPE_UINT64: {
770 uint64_t u;
771
772 r = sd_bus_message_read_basic(property, type, &u);
773 if (r < 0)
774 return r;
775
776 /* Yes, heuristics! But we can change this check
777 * should it turn out to not be sufficient */
778
779 if (endswith(name, "Timestamp")) {
780 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
781
782 t = format_timestamp(timestamp, sizeof(timestamp), u);
783 if (t || all)
784 print_property(name, "%s", strempty(t));
785
786 } else if (strstr(name, "USec")) {
787 char timespan[FORMAT_TIMESPAN_MAX];
788
789 print_property(name, "%s", format_timespan(timespan, sizeof(timespan), u, 0));
790 } else
791 print_property(name, "%"PRIu64, u);
792
793 return 1;
794 }
795
796 case SD_BUS_TYPE_INT64: {
797 int64_t i;
798
799 r = sd_bus_message_read_basic(property, type, &i);
800 if (r < 0)
801 return r;
802
803 print_property(name, "%"PRIi64, i);
804
805 return 1;
806 }
807
808 case SD_BUS_TYPE_UINT32: {
809 uint32_t u;
810
811 r = sd_bus_message_read_basic(property, type, &u);
812 if (r < 0)
813 return r;
814
815 if (strstr(name, "UMask") || strstr(name, "Mode"))
816 print_property(name, "%04o", u);
817 else
818 print_property(name, "%"PRIu32, u);
819
820 return 1;
821 }
822
823 case SD_BUS_TYPE_INT32: {
824 int32_t i;
825
826 r = sd_bus_message_read_basic(property, type, &i);
827 if (r < 0)
828 return r;
829
830 print_property(name, "%"PRIi32, i);
831 return 1;
832 }
833
834 case SD_BUS_TYPE_DOUBLE: {
835 double d;
836
837 r = sd_bus_message_read_basic(property, type, &d);
838 if (r < 0)
839 return r;
840
841 print_property(name, "%g", d);
842 return 1;
843 }
844
845 case SD_BUS_TYPE_ARRAY:
846 if (streq(contents, "s")) {
847 bool first = true;
848 const char *str;
849
850 r = sd_bus_message_enter_container(property, SD_BUS_TYPE_ARRAY, contents);
851 if (r < 0)
852 return r;
853
854 while ((r = sd_bus_message_read_basic(property, SD_BUS_TYPE_STRING, &str)) > 0) {
855 _cleanup_free_ char *escaped = NULL;
856
857 if (first && !value)
858 printf("%s=", name);
859
860 escaped = xescape(str, "\n ");
861 if (!escaped)
862 return -ENOMEM;
863
864 printf("%s%s", first ? "" : " ", escaped);
865
866 first = false;
867 }
868 if (r < 0)
869 return r;
870
871 if (first && all && !value)
872 printf("%s=", name);
873 if (!first || all)
874 puts("");
875
876 r = sd_bus_message_exit_container(property);
877 if (r < 0)
878 return r;
879
880 return 1;
881
882 } else if (streq(contents, "y")) {
883 const uint8_t *u;
884 size_t n;
885
886 r = sd_bus_message_read_array(property, SD_BUS_TYPE_BYTE, (const void**) &u, &n);
887 if (r < 0)
888 return r;
889
890 if (all || n > 0) {
891 unsigned int i;
892
893 if (!value)
894 printf("%s=", name);
895
896 for (i = 0; i < n; i++)
897 printf("%02x", u[i]);
898
899 puts("");
900 }
901
902 return 1;
903
904 } else if (streq(contents, "u")) {
905 uint32_t *u;
906 size_t n;
907
908 r = sd_bus_message_read_array(property, SD_BUS_TYPE_UINT32, (const void**) &u, &n);
909 if (r < 0)
910 return r;
911
912 if (all || n > 0) {
913 unsigned int i;
914
915 if (!value)
916 printf("%s=", name);
917
918 for (i = 0; i < n; i++)
919 printf("%08x", u[i]);
920
921 puts("");
922 }
923
924 return 1;
925 }
926
927 break;
928 }
929
930 return 0;
931 }
932
933 int bus_print_all_properties(sd_bus *bus, const char *dest, const char *path, char **filter, bool value, bool all) {
934 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
935 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
936 int r;
937
938 assert(bus);
939 assert(path);
940
941 r = sd_bus_call_method(bus,
942 dest,
943 path,
944 "org.freedesktop.DBus.Properties",
945 "GetAll",
946 &error,
947 &reply,
948 "s", "");
949 if (r < 0)
950 return r;
951
952 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "{sv}");
953 if (r < 0)
954 return r;
955
956 while ((r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
957 const char *name;
958 const char *contents;
959
960 r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &name);
961 if (r < 0)
962 return r;
963
964 if (!filter || strv_find(filter, name)) {
965 r = sd_bus_message_peek_type(reply, NULL, &contents);
966 if (r < 0)
967 return r;
968
969 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_VARIANT, contents);
970 if (r < 0)
971 return r;
972
973 r = bus_print_property(name, reply, value, all);
974 if (r < 0)
975 return r;
976 if (r == 0) {
977 if (all)
978 printf("%s=[unprintable]\n", name);
979 /* skip what we didn't read */
980 r = sd_bus_message_skip(reply, contents);
981 if (r < 0)
982 return r;
983 }
984
985 r = sd_bus_message_exit_container(reply);
986 if (r < 0)
987 return r;
988 } else {
989 r = sd_bus_message_skip(reply, "v");
990 if (r < 0)
991 return r;
992 }
993
994 r = sd_bus_message_exit_container(reply);
995 if (r < 0)
996 return r;
997 }
998 if (r < 0)
999 return r;
1000
1001 r = sd_bus_message_exit_container(reply);
1002 if (r < 0)
1003 return r;
1004
1005 return 0;
1006 }
1007
1008 int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1009 sd_id128_t *p = userdata;
1010 const void *v;
1011 size_t n;
1012 int r;
1013
1014 r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n);
1015 if (r < 0)
1016 return r;
1017
1018 if (n == 0)
1019 *p = SD_ID128_NULL;
1020 else if (n == 16)
1021 memcpy((*p).bytes, v, n);
1022 else
1023 return -EINVAL;
1024
1025 return 0;
1026 }
1027
1028 static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1029 char type;
1030 int r;
1031
1032 r = sd_bus_message_peek_type(m, &type, NULL);
1033 if (r < 0)
1034 return r;
1035
1036 switch (type) {
1037 case SD_BUS_TYPE_STRING: {
1038 const char *s;
1039 char **p = userdata;
1040
1041 r = sd_bus_message_read_basic(m, type, &s);
1042 if (r < 0)
1043 break;
1044
1045 if (isempty(s))
1046 break;
1047
1048 r = free_and_strdup(p, s);
1049 break;
1050 }
1051
1052 case SD_BUS_TYPE_ARRAY: {
1053 _cleanup_strv_free_ char **l = NULL;
1054 char ***p = userdata;
1055
1056 r = bus_message_read_strv_extend(m, &l);
1057 if (r < 0)
1058 break;
1059
1060 strv_free(*p);
1061 *p = l;
1062 l = NULL;
1063
1064 break;
1065 }
1066
1067 case SD_BUS_TYPE_BOOLEAN: {
1068 unsigned b;
1069 bool *p = userdata;
1070
1071 r = sd_bus_message_read_basic(m, type, &b);
1072 if (r < 0)
1073 break;
1074
1075 *p = b;
1076
1077 break;
1078 }
1079
1080 case SD_BUS_TYPE_UINT32: {
1081 uint32_t u;
1082 uint32_t *p = userdata;
1083
1084 r = sd_bus_message_read_basic(m, type, &u);
1085 if (r < 0)
1086 break;
1087
1088 *p = u;
1089
1090 break;
1091 }
1092
1093 case SD_BUS_TYPE_UINT64: {
1094 uint64_t t;
1095 uint64_t *p = userdata;
1096
1097 r = sd_bus_message_read_basic(m, type, &t);
1098 if (r < 0)
1099 break;
1100
1101 *p = t;
1102
1103 break;
1104 }
1105
1106 default:
1107 break;
1108 }
1109
1110 return r;
1111 }
1112
1113 int bus_message_map_all_properties(
1114 sd_bus_message *m,
1115 const struct bus_properties_map *map,
1116 void *userdata) {
1117
1118 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1119 int r;
1120
1121 assert(m);
1122 assert(map);
1123
1124 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
1125 if (r < 0)
1126 return r;
1127
1128 while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1129 const struct bus_properties_map *prop;
1130 const char *member;
1131 const char *contents;
1132 void *v;
1133 unsigned i;
1134
1135 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
1136 if (r < 0)
1137 return r;
1138
1139 for (i = 0, prop = NULL; map[i].member; i++)
1140 if (streq(map[i].member, member)) {
1141 prop = &map[i];
1142 break;
1143 }
1144
1145 if (prop) {
1146 r = sd_bus_message_peek_type(m, NULL, &contents);
1147 if (r < 0)
1148 return r;
1149
1150 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
1151 if (r < 0)
1152 return r;
1153
1154 v = (uint8_t *)userdata + prop->offset;
1155 if (map[i].set)
1156 r = prop->set(sd_bus_message_get_bus(m), member, m, &error, v);
1157 else
1158 r = map_basic(sd_bus_message_get_bus(m), member, m, &error, v);
1159 if (r < 0)
1160 return r;
1161
1162 r = sd_bus_message_exit_container(m);
1163 if (r < 0)
1164 return r;
1165 } else {
1166 r = sd_bus_message_skip(m, "v");
1167 if (r < 0)
1168 return r;
1169 }
1170
1171 r = sd_bus_message_exit_container(m);
1172 if (r < 0)
1173 return r;
1174 }
1175 if (r < 0)
1176 return r;
1177
1178 return sd_bus_message_exit_container(m);
1179 }
1180
1181 int bus_message_map_properties_changed(
1182 sd_bus_message *m,
1183 const struct bus_properties_map *map,
1184 void *userdata) {
1185
1186 const char *member;
1187 int r, invalidated, i;
1188
1189 assert(m);
1190 assert(map);
1191
1192 r = bus_message_map_all_properties(m, map, userdata);
1193 if (r < 0)
1194 return r;
1195
1196 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s");
1197 if (r < 0)
1198 return r;
1199
1200 invalidated = 0;
1201 while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0)
1202 for (i = 0; map[i].member; i++)
1203 if (streq(map[i].member, member)) {
1204 ++invalidated;
1205 break;
1206 }
1207 if (r < 0)
1208 return r;
1209
1210 r = sd_bus_message_exit_container(m);
1211 if (r < 0)
1212 return r;
1213
1214 return invalidated;
1215 }
1216
1217 int bus_map_all_properties(
1218 sd_bus *bus,
1219 const char *destination,
1220 const char *path,
1221 const struct bus_properties_map *map,
1222 void *userdata) {
1223
1224 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1225 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1226 int r;
1227
1228 assert(bus);
1229 assert(destination);
1230 assert(path);
1231 assert(map);
1232
1233 r = sd_bus_call_method(
1234 bus,
1235 destination,
1236 path,
1237 "org.freedesktop.DBus.Properties",
1238 "GetAll",
1239 &error,
1240 &m,
1241 "s", "");
1242 if (r < 0)
1243 return r;
1244
1245 return bus_message_map_all_properties(m, map, userdata);
1246 }
1247
1248 int bus_connect_transport(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1249 int r;
1250
1251 assert(transport >= 0);
1252 assert(transport < _BUS_TRANSPORT_MAX);
1253 assert(bus);
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
1280 return r;
1281 }
1282
1283 int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1284 int r;
1285
1286 assert(transport >= 0);
1287 assert(transport < _BUS_TRANSPORT_MAX);
1288 assert(bus);
1289
1290 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1291 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1292
1293 switch (transport) {
1294
1295 case BUS_TRANSPORT_LOCAL:
1296 if (user)
1297 r = bus_connect_user_systemd(bus);
1298 else
1299 r = bus_connect_system_systemd(bus);
1300
1301 break;
1302
1303 case BUS_TRANSPORT_REMOTE:
1304 r = sd_bus_open_system_remote(bus, host);
1305 break;
1306
1307 case BUS_TRANSPORT_MACHINE:
1308 r = sd_bus_open_system_machine(bus, host);
1309 break;
1310
1311 default:
1312 assert_not_reached("Hmm, unknown transport type.");
1313 }
1314
1315 return r;
1316 }
1317
1318 int bus_property_get_bool(
1319 sd_bus *bus,
1320 const char *path,
1321 const char *interface,
1322 const char *property,
1323 sd_bus_message *reply,
1324 void *userdata,
1325 sd_bus_error *error) {
1326
1327 int b = *(bool*) userdata;
1328
1329 return sd_bus_message_append_basic(reply, 'b', &b);
1330 }
1331
1332 #if __SIZEOF_SIZE_T__ != 8
1333 int bus_property_get_size(
1334 sd_bus *bus,
1335 const char *path,
1336 const char *interface,
1337 const char *property,
1338 sd_bus_message *reply,
1339 void *userdata,
1340 sd_bus_error *error) {
1341
1342 uint64_t sz = *(size_t*) userdata;
1343
1344 return sd_bus_message_append_basic(reply, 't', &sz);
1345 }
1346 #endif
1347
1348 #if __SIZEOF_LONG__ != 8
1349 int bus_property_get_long(
1350 sd_bus *bus,
1351 const char *path,
1352 const char *interface,
1353 const char *property,
1354 sd_bus_message *reply,
1355 void *userdata,
1356 sd_bus_error *error) {
1357
1358 int64_t l = *(long*) userdata;
1359
1360 return sd_bus_message_append_basic(reply, 'x', &l);
1361 }
1362
1363 int bus_property_get_ulong(
1364 sd_bus *bus,
1365 const char *path,
1366 const char *interface,
1367 const char *property,
1368 sd_bus_message *reply,
1369 void *userdata,
1370 sd_bus_error *error) {
1371
1372 uint64_t ul = *(unsigned long*) userdata;
1373
1374 return sd_bus_message_append_basic(reply, 't', &ul);
1375 }
1376 #endif
1377
1378 int bus_log_parse_error(int r) {
1379 return log_error_errno(r, "Failed to parse bus message: %m");
1380 }
1381
1382 int bus_log_create_error(int r) {
1383 return log_error_errno(r, "Failed to create bus message: %m");
1384 }
1385
1386 int bus_parse_unit_info(sd_bus_message *message, UnitInfo *u) {
1387 assert(message);
1388 assert(u);
1389
1390 u->machine = NULL;
1391
1392 return sd_bus_message_read(
1393 message,
1394 "(ssssssouso)",
1395 &u->id,
1396 &u->description,
1397 &u->load_state,
1398 &u->active_state,
1399 &u->sub_state,
1400 &u->following,
1401 &u->unit_path,
1402 &u->job_id,
1403 &u->job_type,
1404 &u->job_path);
1405 }
1406
1407 int bus_append_unit_property_assignment(sd_bus_message *m, const char *assignment) {
1408 const char *eq, *field;
1409 int r, rl;
1410
1411 assert(m);
1412 assert(assignment);
1413
1414 eq = strchr(assignment, '=');
1415 if (!eq) {
1416 log_error("Not an assignment: %s", assignment);
1417 return -EINVAL;
1418 }
1419
1420 r = sd_bus_message_open_container(m, SD_BUS_TYPE_STRUCT, "sv");
1421 if (r < 0)
1422 return bus_log_create_error(r);
1423
1424 field = strndupa(assignment, eq - assignment);
1425 eq++;
1426
1427 if (streq(field, "CPUQuota")) {
1428
1429 if (isempty(eq))
1430 r = sd_bus_message_append(m, "sv", "CPUQuotaPerSecUSec", "t", USEC_INFINITY);
1431 else if (endswith(eq, "%")) {
1432 double percent;
1433
1434 if (sscanf(eq, "%lf%%", &percent) != 1 || percent <= 0) {
1435 log_error("CPU quota '%s' invalid.", eq);
1436 return -EINVAL;
1437 }
1438
1439 r = sd_bus_message_append(m, "sv", "CPUQuotaPerSecUSec", "t", (usec_t) percent * USEC_PER_SEC / 100);
1440 } else {
1441 log_error("CPU quota needs to be in percent.");
1442 return -EINVAL;
1443 }
1444
1445 goto finish;
1446
1447 } else if (streq(field, "EnvironmentFile")) {
1448
1449 r = sd_bus_message_append(m, "sv", "EnvironmentFiles", "a(sb)", 1,
1450 eq[0] == '-' ? eq + 1 : eq,
1451 eq[0] == '-');
1452 goto finish;
1453
1454 } else if (STR_IN_SET(field, "AccuracySec", "RandomizedDelaySec", "RuntimeMaxSec")) {
1455 char *n;
1456 usec_t t;
1457 size_t l;
1458 r = parse_sec(eq, &t);
1459 if (r < 0)
1460 return log_error_errno(r, "Failed to parse %s= parameter: %s", field, eq);
1461
1462 l = strlen(field);
1463 n = newa(char, l + 2);
1464 if (!n)
1465 return log_oom();
1466
1467 /* Change suffix Sec → USec */
1468 strcpy(mempcpy(n, field, l - 3), "USec");
1469 r = sd_bus_message_append(m, "sv", n, "t", t);
1470 goto finish;
1471 }
1472
1473 r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, field);
1474 if (r < 0)
1475 return bus_log_create_error(r);
1476
1477 rl = rlimit_from_string(field);
1478 if (rl >= 0) {
1479 const char *sn;
1480 struct rlimit l;
1481
1482 r = rlimit_parse(rl, eq, &l);
1483 if (r < 0)
1484 return log_error_errno(r, "Failed to parse resource limit: %s", eq);
1485
1486 r = sd_bus_message_append(m, "v", "t", l.rlim_max);
1487 if (r < 0)
1488 return bus_log_create_error(r);
1489
1490 r = sd_bus_message_close_container(m);
1491 if (r < 0)
1492 return bus_log_create_error(r);
1493
1494 r = sd_bus_message_open_container(m, SD_BUS_TYPE_STRUCT, "sv");
1495 if (r < 0)
1496 return bus_log_create_error(r);
1497
1498 sn = strjoina(field, "Soft");
1499 r = sd_bus_message_append(m, "sv", sn, "t", l.rlim_cur);
1500
1501 } else if (STR_IN_SET(field,
1502 "CPUAccounting", "MemoryAccounting", "BlockIOAccounting", "TasksAccounting",
1503 "SendSIGHUP", "SendSIGKILL", "WakeSystem", "DefaultDependencies",
1504 "IgnoreSIGPIPE", "TTYVHangup", "TTYReset", "RemainAfterExit",
1505 "PrivateTmp", "PrivateDevices", "PrivateNetwork", "NoNewPrivileges",
1506 "SyslogLevelPrefix", "Delegate", "RemainAfterElapse")) {
1507
1508 r = parse_boolean(eq);
1509 if (r < 0)
1510 return log_error_errno(r, "Failed to parse boolean assignment %s.", assignment);
1511
1512 r = sd_bus_message_append(m, "v", "b", r);
1513
1514 } else if (streq(field, "MemoryLimit")) {
1515 uint64_t bytes;
1516
1517 if (isempty(eq) || streq(eq, "infinity"))
1518 bytes = (uint64_t) -1;
1519 else {
1520 r = parse_size(eq, 1024, &bytes);
1521 if (r < 0) {
1522 log_error("Failed to parse bytes specification %s", assignment);
1523 return -EINVAL;
1524 }
1525 }
1526
1527 r = sd_bus_message_append(m, "v", "t", bytes);
1528
1529 } else if (streq(field, "TasksMax")) {
1530 uint64_t n;
1531
1532 if (isempty(eq) || streq(eq, "infinity"))
1533 n = (uint64_t) -1;
1534 else {
1535 r = safe_atou64(eq, &n);
1536 if (r < 0) {
1537 log_error("Failed to parse maximum tasks specification %s", assignment);
1538 return -EINVAL;
1539 }
1540 }
1541
1542 r = sd_bus_message_append(m, "v", "t", n);
1543
1544 } else if (STR_IN_SET(field, "CPUShares", "StartupCPUShares")) {
1545 uint64_t u;
1546
1547 r = cg_cpu_shares_parse(eq, &u);
1548 if (r < 0) {
1549 log_error("Failed to parse %s value %s.", field, eq);
1550 return -EINVAL;
1551 }
1552
1553 r = sd_bus_message_append(m, "v", "t", u);
1554
1555 } else if (STR_IN_SET(field, "BlockIOWeight", "StartupBlockIOWeight")) {
1556 uint64_t u;
1557
1558 r = cg_cpu_shares_parse(eq, &u);
1559 if (r < 0) {
1560 log_error("Failed to parse %s value %s.", field, eq);
1561 return -EINVAL;
1562 }
1563
1564 r = sd_bus_message_append(m, "v", "t", u);
1565
1566 } else if (STR_IN_SET(field,
1567 "User", "Group", "DevicePolicy", "KillMode",
1568 "UtmpIdentifier", "UtmpMode", "PAMName", "TTYPath",
1569 "StandardInput", "StandardOutput", "StandardError",
1570 "Description", "Slice", "Type", "WorkingDirectory",
1571 "RootDirectory", "SyslogIdentifier", "ProtectSystem",
1572 "ProtectHome"))
1573 r = sd_bus_message_append(m, "v", "s", eq);
1574
1575 else if (streq(field, "SyslogLevel")) {
1576 int level;
1577
1578 level = log_level_from_string(eq);
1579 if (level < 0) {
1580 log_error("Failed to parse %s value %s.", field, eq);
1581 return -EINVAL;
1582 }
1583
1584 r = sd_bus_message_append(m, "v", "i", level);
1585
1586 } else if (streq(field, "SyslogFacility")) {
1587 int facility;
1588
1589 facility = log_facility_unshifted_from_string(eq);
1590 if (facility < 0) {
1591 log_error("Failed to parse %s value %s.", field, eq);
1592 return -EINVAL;
1593 }
1594
1595 r = sd_bus_message_append(m, "v", "i", facility);
1596
1597 } else if (streq(field, "DeviceAllow")) {
1598
1599 if (isempty(eq))
1600 r = sd_bus_message_append(m, "v", "a(ss)", 0);
1601 else {
1602 const char *path, *rwm, *e;
1603
1604 e = strchr(eq, ' ');
1605 if (e) {
1606 path = strndupa(eq, e - eq);
1607 rwm = e+1;
1608 } else {
1609 path = eq;
1610 rwm = "";
1611 }
1612
1613 if (!path_startswith(path, "/dev")) {
1614 log_error("%s is not a device file in /dev.", path);
1615 return -EINVAL;
1616 }
1617
1618 r = sd_bus_message_append(m, "v", "a(ss)", 1, path, rwm);
1619 }
1620
1621 } else if (STR_IN_SET(field, "BlockIOReadBandwidth", "BlockIOWriteBandwidth")) {
1622
1623 if (isempty(eq))
1624 r = sd_bus_message_append(m, "v", "a(st)", 0);
1625 else {
1626 const char *path, *bandwidth, *e;
1627 uint64_t bytes;
1628
1629 e = strchr(eq, ' ');
1630 if (e) {
1631 path = strndupa(eq, e - eq);
1632 bandwidth = e+1;
1633 } else {
1634 log_error("Failed to parse %s value %s.", field, eq);
1635 return -EINVAL;
1636 }
1637
1638 if (!path_startswith(path, "/dev")) {
1639 log_error("%s is not a device file in /dev.", path);
1640 return -EINVAL;
1641 }
1642
1643 r = parse_size(bandwidth, 1000, &bytes);
1644 if (r < 0) {
1645 log_error("Failed to parse byte value %s.", bandwidth);
1646 return -EINVAL;
1647 }
1648
1649 r = sd_bus_message_append(m, "v", "a(st)", 1, path, bytes);
1650 }
1651
1652 } else if (streq(field, "BlockIODeviceWeight")) {
1653
1654 if (isempty(eq))
1655 r = sd_bus_message_append(m, "v", "a(st)", 0);
1656 else {
1657 const char *path, *weight, *e;
1658 uint64_t u;
1659
1660 e = strchr(eq, ' ');
1661 if (e) {
1662 path = strndupa(eq, e - eq);
1663 weight = e+1;
1664 } else {
1665 log_error("Failed to parse %s value %s.", field, eq);
1666 return -EINVAL;
1667 }
1668
1669 if (!path_startswith(path, "/dev")) {
1670 log_error("%s is not a device file in /dev.", path);
1671 return -EINVAL;
1672 }
1673
1674 r = safe_atou64(weight, &u);
1675 if (r < 0) {
1676 log_error("Failed to parse %s value %s.", field, weight);
1677 return -EINVAL;
1678 }
1679 r = sd_bus_message_append(m, "v", "a(st)", path, u);
1680 }
1681
1682 } else if (streq(field, "Nice")) {
1683 int32_t i;
1684
1685 r = safe_atoi32(eq, &i);
1686 if (r < 0) {
1687 log_error("Failed to parse %s value %s.", field, eq);
1688 return -EINVAL;
1689 }
1690
1691 r = sd_bus_message_append(m, "v", "i", i);
1692
1693 } else if (STR_IN_SET(field, "Environment", "PassEnvironment")) {
1694 const char *p;
1695
1696 r = sd_bus_message_open_container(m, 'v', "as");
1697 if (r < 0)
1698 return bus_log_create_error(r);
1699
1700 r = sd_bus_message_open_container(m, 'a', "s");
1701 if (r < 0)
1702 return bus_log_create_error(r);
1703
1704 p = eq;
1705
1706 for (;;) {
1707 _cleanup_free_ char *word = NULL;
1708
1709 r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES|EXTRACT_CUNESCAPE);
1710 if (r < 0) {
1711 log_error("Failed to parse Environment value %s", eq);
1712 return -EINVAL;
1713 }
1714 if (r == 0)
1715 break;
1716
1717 if (streq(field, "Environment")) {
1718 if (!env_assignment_is_valid(word)) {
1719 log_error("Invalid environment assignment: %s", word);
1720 return -EINVAL;
1721 }
1722 } else { /* PassEnvironment */
1723 if (!env_name_is_valid(word)) {
1724 log_error("Invalid environment variable name: %s", word);
1725 return -EINVAL;
1726 }
1727 }
1728
1729 r = sd_bus_message_append_basic(m, 's', word);
1730 if (r < 0)
1731 return bus_log_create_error(r);
1732 }
1733
1734 r = sd_bus_message_close_container(m);
1735 if (r < 0)
1736 return bus_log_create_error(r);
1737
1738 r = sd_bus_message_close_container(m);
1739
1740 } else if (streq(field, "KillSignal")) {
1741 int sig;
1742
1743 sig = signal_from_string_try_harder(eq);
1744 if (sig < 0) {
1745 log_error("Failed to parse %s value %s.", field, eq);
1746 return -EINVAL;
1747 }
1748
1749 r = sd_bus_message_append(m, "v", "i", sig);
1750
1751 } else if (streq(field, "TimerSlackNSec")) {
1752 nsec_t n;
1753
1754 r = parse_nsec(eq, &n);
1755 if (r < 0) {
1756 log_error("Failed to parse %s value %s", field, eq);
1757 return -EINVAL;
1758 }
1759
1760 r = sd_bus_message_append(m, "v", "t", n);
1761 } else if (streq(field, "OOMScoreAdjust")) {
1762 int oa;
1763
1764 r = safe_atoi(eq, &oa);
1765 if (r < 0) {
1766 log_error("Failed to parse %s value %s", field, eq);
1767 return -EINVAL;
1768 }
1769
1770 if (!oom_score_adjust_is_valid(oa)) {
1771 log_error("OOM score adjust value out of range");
1772 return -EINVAL;
1773 }
1774
1775 r = sd_bus_message_append(m, "v", "i", oa);
1776 } else if (STR_IN_SET(field, "ReadWriteDirectories", "ReadOnlyDirectories", "InaccessibleDirectories")) {
1777 const char *p;
1778
1779 r = sd_bus_message_open_container(m, 'v', "as");
1780 if (r < 0)
1781 return bus_log_create_error(r);
1782
1783 r = sd_bus_message_open_container(m, 'a', "s");
1784 if (r < 0)
1785 return bus_log_create_error(r);
1786
1787 p = eq;
1788
1789 for (;;) {
1790 _cleanup_free_ char *word = NULL;
1791 int offset;
1792
1793 r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES);
1794 if (r < 0) {
1795 log_error("Failed to parse %s value %s", field, eq);
1796 return -EINVAL;
1797 }
1798 if (r == 0)
1799 break;
1800
1801 if (!utf8_is_valid(word)) {
1802 log_error("Failed to parse %s value %s", field, eq);
1803 return -EINVAL;
1804 }
1805
1806 offset = word[0] == '-';
1807 if (!path_is_absolute(word + offset)) {
1808 log_error("Failed to parse %s value %s", field, eq);
1809 return -EINVAL;
1810 }
1811
1812 path_kill_slashes(word + offset);
1813
1814 r = sd_bus_message_append_basic(m, 's', word);
1815 if (r < 0)
1816 return bus_log_create_error(r);
1817 }
1818
1819 r = sd_bus_message_close_container(m);
1820 if (r < 0)
1821 return bus_log_create_error(r);
1822
1823 r = sd_bus_message_close_container(m);
1824
1825 } else if (streq(field, "RuntimeDirectory")) {
1826 const char *p;
1827
1828 r = sd_bus_message_open_container(m, 'v', "as");
1829 if (r < 0)
1830 return bus_log_create_error(r);
1831
1832 r = sd_bus_message_open_container(m, 'a', "s");
1833 if (r < 0)
1834 return bus_log_create_error(r);
1835
1836 p = eq;
1837
1838 for (;;) {
1839 _cleanup_free_ char *word = NULL;
1840
1841 r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES);
1842 if (r < 0)
1843 return log_error_errno(r, "Failed to parse %s value %s", field, eq);
1844
1845 if (r == 0)
1846 break;
1847
1848 r = sd_bus_message_append_basic(m, 's', word);
1849 if (r < 0)
1850 return bus_log_create_error(r);
1851 }
1852
1853 r = sd_bus_message_close_container(m);
1854 if (r < 0)
1855 return bus_log_create_error(r);
1856
1857 r = sd_bus_message_close_container(m);
1858
1859 } else {
1860 log_error("Unknown assignment %s.", assignment);
1861 return -EINVAL;
1862 }
1863
1864 finish:
1865 if (r < 0)
1866 return bus_log_create_error(r);
1867
1868 r = sd_bus_message_close_container(m);
1869 if (r < 0)
1870 return bus_log_create_error(r);
1871
1872 return 0;
1873 }
1874
1875 typedef struct BusWaitForJobs {
1876 sd_bus *bus;
1877 Set *jobs;
1878
1879 char *name;
1880 char *result;
1881
1882 sd_bus_slot *slot_job_removed;
1883 sd_bus_slot *slot_disconnected;
1884 } BusWaitForJobs;
1885
1886 static int match_disconnected(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1887 assert(m);
1888
1889 log_error("Warning! D-Bus connection terminated.");
1890 sd_bus_close(sd_bus_message_get_bus(m));
1891
1892 return 0;
1893 }
1894
1895 static int match_job_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1896 const char *path, *unit, *result;
1897 BusWaitForJobs *d = userdata;
1898 uint32_t id;
1899 char *found;
1900 int r;
1901
1902 assert(m);
1903 assert(d);
1904
1905 r = sd_bus_message_read(m, "uoss", &id, &path, &unit, &result);
1906 if (r < 0) {
1907 bus_log_parse_error(r);
1908 return 0;
1909 }
1910
1911 found = set_remove(d->jobs, (char*) path);
1912 if (!found)
1913 return 0;
1914
1915 free(found);
1916
1917 if (!isempty(result))
1918 d->result = strdup(result);
1919
1920 if (!isempty(unit))
1921 d->name = strdup(unit);
1922
1923 return 0;
1924 }
1925
1926 void bus_wait_for_jobs_free(BusWaitForJobs *d) {
1927 if (!d)
1928 return;
1929
1930 set_free_free(d->jobs);
1931
1932 sd_bus_slot_unref(d->slot_disconnected);
1933 sd_bus_slot_unref(d->slot_job_removed);
1934
1935 sd_bus_unref(d->bus);
1936
1937 free(d->name);
1938 free(d->result);
1939
1940 free(d);
1941 }
1942
1943 int bus_wait_for_jobs_new(sd_bus *bus, BusWaitForJobs **ret) {
1944 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *d = NULL;
1945 int r;
1946
1947 assert(bus);
1948 assert(ret);
1949
1950 d = new0(BusWaitForJobs, 1);
1951 if (!d)
1952 return -ENOMEM;
1953
1954 d->bus = sd_bus_ref(bus);
1955
1956 /* When we are a bus client we match by sender. Direct
1957 * connections OTOH have no initialized sender field, and
1958 * hence we ignore the sender then */
1959 r = sd_bus_add_match(
1960 bus,
1961 &d->slot_job_removed,
1962 bus->bus_client ?
1963 "type='signal',"
1964 "sender='org.freedesktop.systemd1',"
1965 "interface='org.freedesktop.systemd1.Manager',"
1966 "member='JobRemoved',"
1967 "path='/org/freedesktop/systemd1'" :
1968 "type='signal',"
1969 "interface='org.freedesktop.systemd1.Manager',"
1970 "member='JobRemoved',"
1971 "path='/org/freedesktop/systemd1'",
1972 match_job_removed, d);
1973 if (r < 0)
1974 return r;
1975
1976 r = sd_bus_add_match(
1977 bus,
1978 &d->slot_disconnected,
1979 "type='signal',"
1980 "sender='org.freedesktop.DBus.Local',"
1981 "interface='org.freedesktop.DBus.Local',"
1982 "member='Disconnected'",
1983 match_disconnected, d);
1984 if (r < 0)
1985 return r;
1986
1987 *ret = d;
1988 d = NULL;
1989
1990 return 0;
1991 }
1992
1993 static int bus_process_wait(sd_bus *bus) {
1994 int r;
1995
1996 for (;;) {
1997 r = sd_bus_process(bus, NULL);
1998 if (r < 0)
1999 return r;
2000 if (r > 0)
2001 return 0;
2002
2003 r = sd_bus_wait(bus, (uint64_t) -1);
2004 if (r < 0)
2005 return r;
2006 }
2007 }
2008
2009 static int bus_job_get_service_result(BusWaitForJobs *d, char **result) {
2010 _cleanup_free_ char *dbus_path = NULL;
2011
2012 assert(d);
2013 assert(d->name);
2014 assert(result);
2015
2016 dbus_path = unit_dbus_path_from_name(d->name);
2017 if (!dbus_path)
2018 return -ENOMEM;
2019
2020 return sd_bus_get_property_string(d->bus,
2021 "org.freedesktop.systemd1",
2022 dbus_path,
2023 "org.freedesktop.systemd1.Service",
2024 "Result",
2025 NULL,
2026 result);
2027 }
2028
2029 static const struct {
2030 const char *result, *explanation;
2031 } explanations [] = {
2032 { "resources", "a configured resource limit was exceeded" },
2033 { "timeout", "a timeout was exceeded" },
2034 { "exit-code", "the control process exited with error code" },
2035 { "signal", "a fatal signal was delivered to the control process" },
2036 { "core-dump", "a fatal signal was delivered causing the control process to dump core" },
2037 { "watchdog", "the service failed to send watchdog ping" },
2038 { "start-limit", "start of the service was attempted too often" }
2039 };
2040
2041 static void log_job_error_with_service_result(const char* service, const char *result, const char* const* extra_args) {
2042 _cleanup_free_ char *service_shell_quoted = NULL;
2043 const char *systemctl = "systemctl", *journalctl = "journalctl";
2044
2045 assert(service);
2046
2047 service_shell_quoted = shell_maybe_quote(service);
2048
2049 if (extra_args && extra_args[1]) {
2050 _cleanup_free_ char *t;
2051
2052 t = strv_join((char**) extra_args, " ");
2053 systemctl = strjoina("systemctl ", t ?: "<args>", NULL);
2054 journalctl = strjoina("journalctl ", t ?: "<args>", NULL);
2055 }
2056
2057 if (!isempty(result)) {
2058 unsigned i;
2059
2060 for (i = 0; i < ELEMENTSOF(explanations); ++i)
2061 if (streq(result, explanations[i].result))
2062 break;
2063
2064 if (i < ELEMENTSOF(explanations)) {
2065 log_error("Job for %s failed because %s.\n"
2066 "See \"%s status %s\" and \"%s -xe\" for details.\n",
2067 service,
2068 explanations[i].explanation,
2069 systemctl,
2070 service_shell_quoted ?: "<service>",
2071 journalctl);
2072 goto finish;
2073 }
2074 }
2075
2076 log_error("Job for %s failed.\n"
2077 "See \"%s status %s\" and \"%s -xe\" for details.\n",
2078 service,
2079 systemctl,
2080 service_shell_quoted ?: "<service>",
2081 journalctl);
2082
2083 finish:
2084 /* For some results maybe additional explanation is required */
2085 if (streq_ptr(result, "start-limit"))
2086 log_info("To force a start use \"%1$s reset-failed %2$s\"\n"
2087 "followed by \"%1$s start %2$s\" again.",
2088 systemctl,
2089 service_shell_quoted ?: "<service>");
2090 }
2091
2092 static int check_wait_response(BusWaitForJobs *d, bool quiet, const char* const* extra_args) {
2093 int r = 0;
2094
2095 assert(d->result);
2096
2097 if (!quiet) {
2098 if (streq(d->result, "canceled"))
2099 log_error("Job for %s canceled.", strna(d->name));
2100 else if (streq(d->result, "timeout"))
2101 log_error("Job for %s timed out.", strna(d->name));
2102 else if (streq(d->result, "dependency"))
2103 log_error("A dependency job for %s failed. See 'journalctl -xe' for details.", strna(d->name));
2104 else if (streq(d->result, "invalid"))
2105 log_error("%s is not active, cannot reload.", strna(d->name));
2106 else if (streq(d->result, "assert"))
2107 log_error("Assertion failed on job for %s.", strna(d->name));
2108 else if (streq(d->result, "unsupported"))
2109 log_error("Operation on or unit type of %s not supported on this system.", strna(d->name));
2110 else if (!streq(d->result, "done") && !streq(d->result, "skipped")) {
2111 if (d->name) {
2112 int q;
2113 _cleanup_free_ char *result = NULL;
2114
2115 q = bus_job_get_service_result(d, &result);
2116 if (q < 0)
2117 log_debug_errno(q, "Failed to get Result property of service %s: %m", d->name);
2118
2119 log_job_error_with_service_result(d->name, result, extra_args);
2120 } else
2121 log_error("Job failed. See \"journalctl -xe\" for details.");
2122 }
2123 }
2124
2125 if (streq(d->result, "canceled"))
2126 r = -ECANCELED;
2127 else if (streq(d->result, "timeout"))
2128 r = -ETIME;
2129 else if (streq(d->result, "dependency"))
2130 r = -EIO;
2131 else if (streq(d->result, "invalid"))
2132 r = -ENOEXEC;
2133 else if (streq(d->result, "assert"))
2134 r = -EPROTO;
2135 else if (streq(d->result, "unsupported"))
2136 r = -EOPNOTSUPP;
2137 else if (!streq(d->result, "done") && !streq(d->result, "skipped"))
2138 r = -EIO;
2139
2140 return r;
2141 }
2142
2143 int bus_wait_for_jobs(BusWaitForJobs *d, bool quiet, const char* const* extra_args) {
2144 int r = 0;
2145
2146 assert(d);
2147
2148 while (!set_isempty(d->jobs)) {
2149 int q;
2150
2151 q = bus_process_wait(d->bus);
2152 if (q < 0)
2153 return log_error_errno(q, "Failed to wait for response: %m");
2154
2155 if (d->result) {
2156 q = check_wait_response(d, quiet, extra_args);
2157 /* Return the first error as it is most likely to be
2158 * meaningful. */
2159 if (q < 0 && r == 0)
2160 r = q;
2161
2162 log_debug_errno(q, "Got result %s/%m for job %s", strna(d->result), strna(d->name));
2163 }
2164
2165 d->name = mfree(d->name);
2166 d->result = mfree(d->result);
2167 }
2168
2169 return r;
2170 }
2171
2172 int bus_wait_for_jobs_add(BusWaitForJobs *d, const char *path) {
2173 int r;
2174
2175 assert(d);
2176
2177 r = set_ensure_allocated(&d->jobs, &string_hash_ops);
2178 if (r < 0)
2179 return r;
2180
2181 return set_put_strdup(d->jobs, path);
2182 }
2183
2184 int bus_wait_for_jobs_one(BusWaitForJobs *d, const char *path, bool quiet) {
2185 int r;
2186
2187 r = bus_wait_for_jobs_add(d, path);
2188 if (r < 0)
2189 return log_oom();
2190
2191 return bus_wait_for_jobs(d, quiet, NULL);
2192 }
2193
2194 int bus_deserialize_and_dump_unit_file_changes(sd_bus_message *m, bool quiet, UnitFileChange **changes, unsigned *n_changes) {
2195 const char *type, *path, *source;
2196 int r;
2197
2198 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sss)");
2199 if (r < 0)
2200 return bus_log_parse_error(r);
2201
2202 while ((r = sd_bus_message_read(m, "(sss)", &type, &path, &source)) > 0) {
2203 if (!quiet) {
2204 if (streq(type, "symlink"))
2205 log_info("Created symlink from %s to %s.", path, source);
2206 else
2207 log_info("Removed symlink %s.", path);
2208 }
2209
2210 r = unit_file_changes_add(changes, n_changes, streq(type, "symlink") ? UNIT_FILE_SYMLINK : UNIT_FILE_UNLINK, path, source);
2211 if (r < 0)
2212 return r;
2213 }
2214 if (r < 0)
2215 return bus_log_parse_error(r);
2216
2217 r = sd_bus_message_exit_container(m);
2218 if (r < 0)
2219 return bus_log_parse_error(r);
2220
2221 return 0;
2222 }
2223
2224 /**
2225 * bus_path_encode_unique() - encode unique object path
2226 * @b: bus connection or NULL
2227 * @prefix: object path prefix
2228 * @sender_id: unique-name of client, or NULL
2229 * @external_id: external ID to be chosen by client, or NULL
2230 * @ret_path: storage for encoded object path pointer
2231 *
2232 * Whenever we provide a bus API that allows clients to create and manage
2233 * server-side objects, we need to provide a unique name for these objects. If
2234 * we let the server choose the name, we suffer from a race condition: If a
2235 * client creates an object asynchronously, it cannot destroy that object until
2236 * it received the method reply. It cannot know the name of the new object,
2237 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
2238 *
2239 * Therefore, many APIs allow the client to choose the unique name for newly
2240 * created objects. There're two problems to solve, though:
2241 * 1) Object names are usually defined via dbus object paths, which are
2242 * usually globally namespaced. Therefore, multiple clients must be able
2243 * to choose unique object names without interference.
2244 * 2) If multiple libraries share the same bus connection, they must be
2245 * able to choose unique object names without interference.
2246 * The first problem is solved easily by prefixing a name with the
2247 * unique-bus-name of a connection. The server side must enforce this and
2248 * reject any other name. The second problem is solved by providing unique
2249 * suffixes from within sd-bus.
2250 *
2251 * This helper allows clients to create unique object-paths. It uses the
2252 * template '/prefix/sender_id/external_id' and returns the new path in
2253 * @ret_path (must be freed by the caller).
2254 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
2255 * NULL, this function allocates a unique suffix via @b (by requesting a new
2256 * cookie). If both @sender_id and @external_id are given, @b can be passed as
2257 * NULL.
2258 *
2259 * Returns: 0 on success, negative error code on failure.
2260 */
2261 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
2262 _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
2263 char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
2264 int r;
2265
2266 assert_return(b || (sender_id && external_id), -EINVAL);
2267 assert_return(object_path_is_valid(prefix), -EINVAL);
2268 assert_return(ret_path, -EINVAL);
2269
2270 if (!sender_id) {
2271 r = sd_bus_get_unique_name(b, &sender_id);
2272 if (r < 0)
2273 return r;
2274 }
2275
2276 if (!external_id) {
2277 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
2278 external_id = external_buf;
2279 }
2280
2281 sender_label = bus_label_escape(sender_id);
2282 if (!sender_label)
2283 return -ENOMEM;
2284
2285 external_label = bus_label_escape(external_id);
2286 if (!external_label)
2287 return -ENOMEM;
2288
2289 p = strjoin(prefix, "/", sender_label, "/", external_label, NULL);
2290 if (!p)
2291 return -ENOMEM;
2292
2293 *ret_path = p;
2294 return 0;
2295 }
2296
2297 /**
2298 * bus_path_decode_unique() - decode unique object path
2299 * @path: object path to decode
2300 * @prefix: object path prefix
2301 * @ret_sender: output parameter for sender-id label
2302 * @ret_external: output parameter for external-id label
2303 *
2304 * This does the reverse of bus_path_encode_unique() (see its description for
2305 * details). Both trailing labels, sender-id and external-id, are unescaped and
2306 * returned in the given output parameters (the caller must free them).
2307 *
2308 * Note that this function returns 0 if the path does not match the template
2309 * (see bus_path_encode_unique()), 1 if it matched.
2310 *
2311 * Returns: Negative error code on failure, 0 if the given object path does not
2312 * match the template (return parameters are set to NULL), 1 if it was
2313 * parsed successfully (return parameters contain allocated labels).
2314 */
2315 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
2316 const char *p, *q;
2317 char *sender, *external;
2318
2319 assert(object_path_is_valid(path));
2320 assert(object_path_is_valid(prefix));
2321 assert(ret_sender);
2322 assert(ret_external);
2323
2324 p = object_path_startswith(path, prefix);
2325 if (!p) {
2326 *ret_sender = NULL;
2327 *ret_external = NULL;
2328 return 0;
2329 }
2330
2331 q = strchr(p, '/');
2332 if (!q) {
2333 *ret_sender = NULL;
2334 *ret_external = NULL;
2335 return 0;
2336 }
2337
2338 sender = bus_label_unescape_n(p, q - p);
2339 external = bus_label_unescape(q + 1);
2340 if (!sender || !external) {
2341 free(sender);
2342 free(external);
2343 return -ENOMEM;
2344 }
2345
2346 *ret_sender = sender;
2347 *ret_external = external;
2348 return 1;
2349 }
2350
2351 bool is_kdbus_wanted(void) {
2352 _cleanup_free_ char *value = NULL;
2353 #ifdef ENABLE_KDBUS
2354 const bool configured = true;
2355 #else
2356 const bool configured = false;
2357 #endif
2358
2359 int r;
2360
2361 if (get_proc_cmdline_key("kdbus", NULL) > 0)
2362 return true;
2363
2364 r = get_proc_cmdline_key("kdbus=", &value);
2365 if (r <= 0)
2366 return configured;
2367
2368 return parse_boolean(value) == 1;
2369 }
2370
2371 bool is_kdbus_available(void) {
2372 _cleanup_close_ int fd = -1;
2373 struct kdbus_cmd cmd = { .size = sizeof(cmd), .flags = KDBUS_FLAG_NEGOTIATE };
2374
2375 if (!is_kdbus_wanted())
2376 return false;
2377
2378 fd = open("/sys/fs/kdbus/control", O_RDWR | O_CLOEXEC | O_NONBLOCK | O_NOCTTY);
2379 if (fd < 0)
2380 return false;
2381
2382 return ioctl(fd, KDBUS_CMD_BUS_MAKE, &cmd) >= 0;
2383 }
2384
2385 int bus_property_get_rlimit(
2386 sd_bus *bus,
2387 const char *path,
2388 const char *interface,
2389 const char *property,
2390 sd_bus_message *reply,
2391 void *userdata,
2392 sd_bus_error *error) {
2393
2394 struct rlimit *rl;
2395 uint64_t u;
2396 rlim_t x;
2397 const char *is_soft;
2398
2399 assert(bus);
2400 assert(reply);
2401 assert(userdata);
2402
2403 is_soft = endswith(property, "Soft");
2404 rl = *(struct rlimit**) userdata;
2405 if (rl)
2406 x = is_soft ? rl->rlim_cur : rl->rlim_max;
2407 else {
2408 struct rlimit buf = {};
2409 int z;
2410 const char *s;
2411
2412 s = is_soft ? strndupa(property, is_soft - property) : property;
2413
2414 z = rlimit_from_string(strstr(s, "Limit"));
2415 assert(z >= 0);
2416
2417 getrlimit(z, &buf);
2418 x = is_soft ? buf.rlim_cur : buf.rlim_max;
2419 }
2420
2421 /* rlim_t might have different sizes, let's map
2422 * RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on
2423 * all archs */
2424 u = x == RLIM_INFINITY ? (uint64_t) -1 : (uint64_t) x;
2425
2426 return sd_bus_message_append(reply, "t", u);
2427 }