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