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