chiark / gitweb /
path-util: add a function to peek into a container and guess elogind version
[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
1024         case SD_BUS_TYPE_STRING: {
1025                 char **p = userdata;
1026                 const char *s;
1027
1028                 r = sd_bus_message_read_basic(m, type, &s);
1029                 if (r < 0)
1030                         return r;
1031
1032                 if (isempty(s))
1033                         s = NULL;
1034
1035                 return free_and_strdup(p, s);
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                         return r;
1045
1046                 strv_free(*p);
1047                 *p = l;
1048                 l = NULL;
1049                 return 0;
1050         }
1051
1052         case SD_BUS_TYPE_BOOLEAN: {
1053                 unsigned b;
1054                 int *p = userdata;
1055
1056                 r = sd_bus_message_read_basic(m, type, &b);
1057                 if (r < 0)
1058                         return r;
1059
1060                 *p = b;
1061                 return 0;
1062         }
1063
1064         case SD_BUS_TYPE_INT32:
1065         case SD_BUS_TYPE_UINT32: {
1066                 uint32_t u, *p = userdata;
1067
1068                 r = sd_bus_message_read_basic(m, type, &u);
1069                 if (r < 0)
1070                         return r;
1071
1072                 *p = u;
1073                 return 0;
1074         }
1075
1076         case SD_BUS_TYPE_INT64:
1077         case SD_BUS_TYPE_UINT64: {
1078                 uint64_t t, *p = userdata;
1079
1080                 r = sd_bus_message_read_basic(m, type, &t);
1081                 if (r < 0)
1082                         return r;
1083
1084                 *p = t;
1085                 return 0;
1086         }
1087
1088         case SD_BUS_TYPE_DOUBLE: {
1089                 double d, *p = userdata;
1090
1091                 r = sd_bus_message_read_basic(m, type, &d);
1092                 if (r < 0)
1093                         return r;
1094
1095                 *p = d;
1096                 return 0;
1097         }}
1098
1099         return -EOPNOTSUPP;
1100 }
1101
1102 int bus_message_map_all_properties(
1103                 sd_bus_message *m,
1104                 const struct bus_properties_map *map,
1105                 void *userdata) {
1106
1107         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1108         int r;
1109
1110         assert(m);
1111         assert(map);
1112
1113         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
1114         if (r < 0)
1115                 return r;
1116
1117         while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1118                 const struct bus_properties_map *prop;
1119                 const char *member;
1120                 const char *contents;
1121                 void *v;
1122                 unsigned i;
1123
1124                 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
1125                 if (r < 0)
1126                         return r;
1127
1128                 for (i = 0, prop = NULL; map[i].member; i++)
1129                         if (streq(map[i].member, member)) {
1130                                 prop = &map[i];
1131                                 break;
1132                         }
1133
1134                 if (prop) {
1135                         r = sd_bus_message_peek_type(m, NULL, &contents);
1136                         if (r < 0)
1137                                 return r;
1138
1139                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
1140                         if (r < 0)
1141                                 return r;
1142
1143                         v = (uint8_t *)userdata + prop->offset;
1144                         if (map[i].set)
1145                                 r = prop->set(sd_bus_message_get_bus(m), member, m, &error, v);
1146                         else
1147                                 r = map_basic(sd_bus_message_get_bus(m), member, m, &error, v);
1148                         if (r < 0)
1149                                 return r;
1150
1151                         r = sd_bus_message_exit_container(m);
1152                         if (r < 0)
1153                                 return r;
1154                 } else {
1155                         r = sd_bus_message_skip(m, "v");
1156                         if (r < 0)
1157                                 return r;
1158                 }
1159
1160                 r = sd_bus_message_exit_container(m);
1161                 if (r < 0)
1162                         return r;
1163         }
1164         if (r < 0)
1165                 return r;
1166
1167         return sd_bus_message_exit_container(m);
1168 }
1169
1170 #if 0 /// UNNEEDED by elogind
1171 int bus_message_map_properties_changed(
1172                 sd_bus_message *m,
1173                 const struct bus_properties_map *map,
1174                 void *userdata) {
1175
1176         const char *member;
1177         int r, invalidated, i;
1178
1179         assert(m);
1180         assert(map);
1181
1182         r = bus_message_map_all_properties(m, map, userdata);
1183         if (r < 0)
1184                 return r;
1185
1186         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s");
1187         if (r < 0)
1188                 return r;
1189
1190         invalidated = 0;
1191         while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0)
1192                 for (i = 0; map[i].member; i++)
1193                         if (streq(map[i].member, member)) {
1194                                 ++invalidated;
1195                                 break;
1196                         }
1197         if (r < 0)
1198                 return r;
1199
1200         r = sd_bus_message_exit_container(m);
1201         if (r < 0)
1202                 return r;
1203
1204         return invalidated;
1205 }
1206 #endif // 0
1207
1208 int bus_map_all_properties(
1209                 sd_bus *bus,
1210                 const char *destination,
1211                 const char *path,
1212                 const struct bus_properties_map *map,
1213                 void *userdata) {
1214
1215         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1216         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1217         int r;
1218
1219         assert(bus);
1220         assert(destination);
1221         assert(path);
1222         assert(map);
1223
1224         r = sd_bus_call_method(
1225                         bus,
1226                         destination,
1227                         path,
1228                         "org.freedesktop.DBus.Properties",
1229                         "GetAll",
1230                         &error,
1231                         &m,
1232                         "s", "");
1233         if (r < 0)
1234                 return r;
1235
1236         return bus_message_map_all_properties(m, map, userdata);
1237 }
1238
1239 int bus_connect_transport(BusTransport transport, const char *host, bool user, sd_bus **ret) {
1240         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1241         int r;
1242
1243         assert(transport >= 0);
1244         assert(transport < _BUS_TRANSPORT_MAX);
1245         assert(ret);
1246
1247         assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1248         assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1249
1250         switch (transport) {
1251
1252         case BUS_TRANSPORT_LOCAL:
1253 #if 0 /// elogind does not support a user bus
1254                 if (user)
1255                         r = sd_bus_default_user(&bus);
1256                 else
1257 #endif // 0
1258                         r = sd_bus_default_system(&bus);
1259
1260                 break;
1261
1262         case BUS_TRANSPORT_REMOTE:
1263                 r = sd_bus_open_system_remote(&bus, host);
1264                 break;
1265
1266         case BUS_TRANSPORT_MACHINE:
1267                 r = sd_bus_open_system_machine(&bus, host);
1268                 break;
1269
1270         default:
1271                 assert_not_reached("Hmm, unknown transport type.");
1272         }
1273         if (r < 0)
1274                 return r;
1275
1276         r = sd_bus_set_exit_on_disconnect(bus, true);
1277         if (r < 0)
1278                 return r;
1279
1280         *ret = bus;
1281         bus = NULL;
1282
1283         return 0;
1284 }
1285
1286 #if 0 /// UNNEEDED by elogind
1287 int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1288         int r;
1289
1290         assert(transport >= 0);
1291         assert(transport < _BUS_TRANSPORT_MAX);
1292         assert(bus);
1293
1294         assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1295         assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1296
1297         switch (transport) {
1298
1299         case BUS_TRANSPORT_LOCAL:
1300                 if (user)
1301                         r = bus_connect_user_systemd(bus);
1302                 else
1303                         r = bus_connect_system_systemd(bus);
1304
1305                 break;
1306
1307         case BUS_TRANSPORT_REMOTE:
1308                 r = sd_bus_open_system_remote(bus, host);
1309                 break;
1310
1311         case BUS_TRANSPORT_MACHINE:
1312                 r = sd_bus_open_system_machine(bus, host);
1313                 break;
1314
1315         default:
1316                 assert_not_reached("Hmm, unknown transport type.");
1317         }
1318
1319         return r;
1320 }
1321 #endif // 0
1322
1323 int bus_property_get_bool(
1324                 sd_bus *bus,
1325                 const char *path,
1326                 const char *interface,
1327                 const char *property,
1328                 sd_bus_message *reply,
1329                 void *userdata,
1330                 sd_bus_error *error) {
1331
1332         int b = *(bool*) userdata;
1333
1334         return sd_bus_message_append_basic(reply, 'b', &b);
1335 }
1336
1337 int bus_property_get_id128(
1338                 sd_bus *bus,
1339                 const char *path,
1340                 const char *interface,
1341                 const char *property,
1342                 sd_bus_message *reply,
1343                 void *userdata,
1344                 sd_bus_error *error) {
1345
1346         sd_id128_t *id = userdata;
1347
1348         if (sd_id128_is_null(*id)) /* Add an empty array if the ID is zero */
1349                 return sd_bus_message_append(reply, "ay", 0);
1350         else
1351                 return sd_bus_message_append_array(reply, 'y', id->bytes, 16);
1352 }
1353
1354 #if __SIZEOF_SIZE_T__ != 8
1355 int bus_property_get_size(
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 sz = *(size_t*) userdata;
1365
1366         return sd_bus_message_append_basic(reply, 't', &sz);
1367 }
1368 #endif
1369
1370 #if __SIZEOF_LONG__ != 8
1371 int bus_property_get_long(
1372                 sd_bus *bus,
1373                 const char *path,
1374                 const char *interface,
1375                 const char *property,
1376                 sd_bus_message *reply,
1377                 void *userdata,
1378                 sd_bus_error *error) {
1379
1380         int64_t l = *(long*) userdata;
1381
1382         return sd_bus_message_append_basic(reply, 'x', &l);
1383 }
1384
1385 int bus_property_get_ulong(
1386                 sd_bus *bus,
1387                 const char *path,
1388                 const char *interface,
1389                 const char *property,
1390                 sd_bus_message *reply,
1391                 void *userdata,
1392                 sd_bus_error *error) {
1393
1394         uint64_t ul = *(unsigned long*) userdata;
1395
1396         return sd_bus_message_append_basic(reply, 't', &ul);
1397 }
1398 #endif
1399
1400 int bus_log_parse_error(int r) {
1401         return log_error_errno(r, "Failed to parse bus message: %m");
1402 }
1403
1404 #if 0 /// UNNEEDED by elogind
1405 int bus_log_create_error(int r) {
1406         return log_error_errno(r, "Failed to create bus message: %m");
1407 }
1408
1409 #endif // 0
1410 #if 0 /// UNNEEDED by elogind
1411 /**
1412  * bus_path_encode_unique() - encode unique object path
1413  * @b: bus connection or NULL
1414  * @prefix: object path prefix
1415  * @sender_id: unique-name of client, or NULL
1416  * @external_id: external ID to be chosen by client, or NULL
1417  * @ret_path: storage for encoded object path pointer
1418  *
1419  * Whenever we provide a bus API that allows clients to create and manage
1420  * server-side objects, we need to provide a unique name for these objects. If
1421  * we let the server choose the name, we suffer from a race condition: If a
1422  * client creates an object asynchronously, it cannot destroy that object until
1423  * it received the method reply. It cannot know the name of the new object,
1424  * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
1425  *
1426  * Therefore, many APIs allow the client to choose the unique name for newly
1427  * created objects. There're two problems to solve, though:
1428  *    1) Object names are usually defined via dbus object paths, which are
1429  *       usually globally namespaced. Therefore, multiple clients must be able
1430  *       to choose unique object names without interference.
1431  *    2) If multiple libraries share the same bus connection, they must be
1432  *       able to choose unique object names without interference.
1433  * The first problem is solved easily by prefixing a name with the
1434  * unique-bus-name of a connection. The server side must enforce this and
1435  * reject any other name. The second problem is solved by providing unique
1436  * suffixes from within sd-bus.
1437  *
1438  * This helper allows clients to create unique object-paths. It uses the
1439  * template '/prefix/sender_id/external_id' and returns the new path in
1440  * @ret_path (must be freed by the caller).
1441  * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
1442  * NULL, this function allocates a unique suffix via @b (by requesting a new
1443  * cookie). If both @sender_id and @external_id are given, @b can be passed as
1444  * NULL.
1445  *
1446  * Returns: 0 on success, negative error code on failure.
1447  */
1448 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
1449         _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
1450         char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
1451         int r;
1452
1453         assert_return(b || (sender_id && external_id), -EINVAL);
1454         assert_return(object_path_is_valid(prefix), -EINVAL);
1455         assert_return(ret_path, -EINVAL);
1456
1457         if (!sender_id) {
1458                 r = sd_bus_get_unique_name(b, &sender_id);
1459                 if (r < 0)
1460                         return r;
1461         }
1462
1463         if (!external_id) {
1464                 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
1465                 external_id = external_buf;
1466         }
1467
1468         sender_label = bus_label_escape(sender_id);
1469         if (!sender_label)
1470                 return -ENOMEM;
1471
1472         external_label = bus_label_escape(external_id);
1473         if (!external_label)
1474                 return -ENOMEM;
1475
1476         p = strjoin(prefix, "/", sender_label, "/", external_label, NULL);
1477         if (!p)
1478                 return -ENOMEM;
1479
1480         *ret_path = p;
1481         return 0;
1482 }
1483
1484 /**
1485  * bus_path_decode_unique() - decode unique object path
1486  * @path: object path to decode
1487  * @prefix: object path prefix
1488  * @ret_sender: output parameter for sender-id label
1489  * @ret_external: output parameter for external-id label
1490  *
1491  * This does the reverse of bus_path_encode_unique() (see its description for
1492  * details). Both trailing labels, sender-id and external-id, are unescaped and
1493  * returned in the given output parameters (the caller must free them).
1494  *
1495  * Note that this function returns 0 if the path does not match the template
1496  * (see bus_path_encode_unique()), 1 if it matched.
1497  *
1498  * Returns: Negative error code on failure, 0 if the given object path does not
1499  *          match the template (return parameters are set to NULL), 1 if it was
1500  *          parsed successfully (return parameters contain allocated labels).
1501  */
1502 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
1503         const char *p, *q;
1504         char *sender, *external;
1505
1506         assert(object_path_is_valid(path));
1507         assert(object_path_is_valid(prefix));
1508         assert(ret_sender);
1509         assert(ret_external);
1510
1511         p = object_path_startswith(path, prefix);
1512         if (!p) {
1513                 *ret_sender = NULL;
1514                 *ret_external = NULL;
1515                 return 0;
1516         }
1517
1518         q = strchr(p, '/');
1519         if (!q) {
1520                 *ret_sender = NULL;
1521                 *ret_external = NULL;
1522                 return 0;
1523         }
1524
1525         sender = bus_label_unescape_n(p, q - p);
1526         external = bus_label_unescape(q + 1);
1527         if (!sender || !external) {
1528                 free(sender);
1529                 free(external);
1530                 return -ENOMEM;
1531         }
1532
1533         *ret_sender = sender;
1534         *ret_external = external;
1535         return 1;
1536 }
1537 #endif // 0
1538
1539 #if 0 /// UNNEEDED by elogind
1540 int bus_property_get_rlimit(
1541                 sd_bus *bus,
1542                 const char *path,
1543                 const char *interface,
1544                 const char *property,
1545                 sd_bus_message *reply,
1546                 void *userdata,
1547                 sd_bus_error *error) {
1548
1549         struct rlimit *rl;
1550         uint64_t u;
1551         rlim_t x;
1552         const char *is_soft;
1553
1554         assert(bus);
1555         assert(reply);
1556         assert(userdata);
1557
1558         is_soft = endswith(property, "Soft");
1559         rl = *(struct rlimit**) userdata;
1560         if (rl)
1561                 x = is_soft ? rl->rlim_cur : rl->rlim_max;
1562         else {
1563                 struct rlimit buf = {};
1564                 int z;
1565                 const char *s;
1566
1567                 s = is_soft ? strndupa(property, is_soft - property) : property;
1568
1569                 z = rlimit_from_string(strstr(s, "Limit"));
1570                 assert(z >= 0);
1571
1572                 getrlimit(z, &buf);
1573                 x = is_soft ? buf.rlim_cur : buf.rlim_max;
1574         }
1575
1576         /* rlim_t might have different sizes, let's map
1577          * RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on
1578          * all archs */
1579         u = x == RLIM_INFINITY ? (uint64_t) -1 : (uint64_t) x;
1580
1581         return sd_bus_message_append(reply, "t", u);
1582 }
1583 #endif // 0