chiark / gitweb /
tree-wide: remove Lennart's copyright lines
[elogind.git] / src / shared / bus-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <inttypes.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/ioctl.h>
10 #include <sys/resource.h>
11 #include <sys/socket.h>
12 #include <unistd.h>
13
14 #include "sd-bus-protocol.h"
15 #include "sd-bus.h"
16 #include "sd-daemon.h"
17 #include "sd-event.h"
18 #include "sd-id128.h"
19
20 #include "alloc-util.h"
21 #include "bus-internal.h"
22 #include "bus-label.h"
23 #include "bus-message.h"
24 #include "bus-util.h"
25 #include "cap-list.h"
26 #include "cgroup-util.h"
27 #include "def.h"
28 #include "escape.h"
29 #include "fd-util.h"
30 #include "missing.h"
31 #include "mount-util.h"
32 #include "nsflags.h"
33 #include "parse-util.h"
34 #include "proc-cmdline.h"
35 //#include "rlimit-util.h"
36 #include "stdio-util.h"
37 #include "strv.h"
38 #include "user-util.h"
39
40 #if 0 /// UNNEEDED by elogind
41 static int name_owner_change_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
42         sd_event *e = userdata;
43
44         assert(m);
45         assert(e);
46
47         sd_bus_close(sd_bus_message_get_bus(m));
48         sd_event_exit(e, 0);
49
50         return 1;
51 }
52
53 int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name) {
54         const char *match;
55         const char *unique;
56         int r;
57
58         assert(e);
59         assert(bus);
60         assert(name);
61
62         /* We unregister the name here and then wait for the
63          * NameOwnerChanged signal for this event to arrive before we
64          * quit. We do this in order to make sure that any queued
65          * requests are still processed before we really exit. */
66
67         r = sd_bus_get_unique_name(bus, &unique);
68         if (r < 0)
69                 return r;
70
71         match = strjoina(
72                         "sender='org.freedesktop.DBus',"
73                         "type='signal',"
74                         "interface='org.freedesktop.DBus',"
75                         "member='NameOwnerChanged',"
76                         "path='/org/freedesktop/DBus',"
77                         "arg0='", name, "',",
78                         "arg1='", unique, "',",
79                         "arg2=''");
80
81         r = sd_bus_add_match_async(bus, NULL, match, name_owner_change_callback, NULL, e);
82         if (r < 0)
83                 return r;
84
85         r = sd_bus_release_name_async(bus, NULL, name, NULL, NULL);
86         if (r < 0)
87                 return r;
88
89         return 0;
90 }
91
92 int bus_event_loop_with_idle(
93                 sd_event *e,
94                 sd_bus *bus,
95                 const char *name,
96                 usec_t timeout,
97                 check_idle_t check_idle,
98                 void *userdata) {
99         bool exiting = false;
100         int r, code;
101
102         assert(e);
103         assert(bus);
104         assert(name);
105
106         for (;;) {
107                 bool idle;
108
109                 r = sd_event_get_state(e);
110                 if (r < 0)
111                         return r;
112                 if (r == SD_EVENT_FINISHED)
113                         break;
114
115                 if (check_idle)
116                         idle = check_idle(userdata);
117                 else
118                         idle = true;
119
120                 r = sd_event_run(e, exiting || !idle ? (uint64_t) -1 : timeout);
121                 if (r < 0)
122                         return r;
123
124                 if (r == 0 && !exiting && idle) {
125
126                         r = sd_bus_try_close(bus);
127                         if (r == -EBUSY)
128                                 continue;
129
130                         /* Fallback for dbus1 connections: we
131                          * unregister the name and wait for the
132                          * response to come through for it */
133                         if (r == -EOPNOTSUPP) {
134
135                                 /* Inform the service manager that we
136                                  * are going down, so that it will
137                                  * queue all further start requests,
138                                  * instead of assuming we are already
139                                  * running. */
140                                 sd_notify(false, "STOPPING=1");
141
142                                 r = bus_async_unregister_and_exit(e, bus, name);
143                                 if (r < 0)
144                                         return r;
145
146                                 exiting = true;
147                                 continue;
148                         }
149
150                         if (r < 0)
151                                 return r;
152
153                         sd_event_exit(e, 0);
154                         break;
155                 }
156         }
157
158         r = sd_event_get_exit_code(e, &code);
159         if (r < 0)
160                 return r;
161
162         return code;
163 }
164 #endif // 0
165
166 int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error) {
167         _cleanup_(sd_bus_message_unrefp) sd_bus_message *rep = NULL;
168         int r, has_owner = 0;
169
170         assert(c);
171         assert(name);
172
173         r = sd_bus_call_method(c,
174                                "org.freedesktop.DBus",
175                                "/org/freedesktop/dbus",
176                                "org.freedesktop.DBus",
177                                "NameHasOwner",
178                                error,
179                                &rep,
180                                "s",
181                                name);
182         if (r < 0)
183                 return r;
184
185         r = sd_bus_message_read_basic(rep, 'b', &has_owner);
186         if (r < 0)
187                 return sd_bus_error_set_errno(error, r);
188
189         return has_owner;
190 }
191
192 static int check_good_user(sd_bus_message *m, uid_t good_user) {
193         _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
194         uid_t sender_uid;
195         int r;
196
197         assert(m);
198
199         if (good_user == UID_INVALID)
200                 return 0;
201
202         r = sd_bus_query_sender_creds(m, SD_BUS_CREDS_EUID, &creds);
203         if (r < 0)
204                 return r;
205
206         /* Don't trust augmented credentials for authorization */
207         assert_return((sd_bus_creds_get_augmented_mask(creds) & SD_BUS_CREDS_EUID) == 0, -EPERM);
208
209         r = sd_bus_creds_get_euid(creds, &sender_uid);
210         if (r < 0)
211                 return r;
212
213         return sender_uid == good_user;
214 }
215
216 int bus_test_polkit(
217                 sd_bus_message *call,
218                 int capability,
219                 const char *action,
220                 const char **details,
221                 uid_t good_user,
222                 bool *_challenge,
223                 sd_bus_error *e) {
224
225         int r;
226
227         assert(call);
228         assert(action);
229
230         /* Tests non-interactively! */
231
232         r = check_good_user(call, good_user);
233         if (r != 0)
234                 return r;
235
236         r = sd_bus_query_sender_privilege(call, capability);
237         if (r < 0)
238                 return r;
239         else if (r > 0)
240                 return 1;
241 #if ENABLE_POLKIT
242         else {
243                 _cleanup_(sd_bus_message_unrefp) sd_bus_message *request = NULL;
244                 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
245                 int authorized = false, challenge = false;
246                 const char *sender, **k, **v;
247
248                 sender = sd_bus_message_get_sender(call);
249                 if (!sender)
250                         return -EBADMSG;
251
252                 r = sd_bus_message_new_method_call(
253                                 call->bus,
254                                 &request,
255                                 "org.freedesktop.PolicyKit1",
256                                 "/org/freedesktop/PolicyKit1/Authority",
257                                 "org.freedesktop.PolicyKit1.Authority",
258                                 "CheckAuthorization");
259                 if (r < 0)
260                         return r;
261
262                 r = sd_bus_message_append(
263                                 request,
264                                 "(sa{sv})s",
265                                 "system-bus-name", 1, "name", "s", sender,
266                                 action);
267                 if (r < 0)
268                         return r;
269
270                 r = sd_bus_message_open_container(request, 'a', "{ss}");
271                 if (r < 0)
272                         return r;
273
274                 STRV_FOREACH_PAIR(k, v, details) {
275                         r = sd_bus_message_append(request, "{ss}", *k, *v);
276                         if (r < 0)
277                                 return r;
278                 }
279
280                 r = sd_bus_message_close_container(request);
281                 if (r < 0)
282                         return r;
283
284                 r = sd_bus_message_append(request, "us", 0, NULL);
285                 if (r < 0)
286                         return r;
287
288                 r = sd_bus_call(call->bus, request, 0, e, &reply);
289                 if (r < 0) {
290                         /* Treat no PK available as access denied */
291                         if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN)) {
292                                 sd_bus_error_free(e);
293                                 return -EACCES;
294                         }
295
296                         return r;
297                 }
298
299                 r = sd_bus_message_enter_container(reply, 'r', "bba{ss}");
300                 if (r < 0)
301                         return r;
302
303                 r = sd_bus_message_read(reply, "bb", &authorized, &challenge);
304                 if (r < 0)
305                         return r;
306
307                 if (authorized)
308                         return 1;
309
310                 if (_challenge) {
311                         *_challenge = challenge;
312                         return 0;
313                 }
314         }
315 #endif
316
317         return -EACCES;
318 }
319
320 #if ENABLE_POLKIT
321
322 typedef struct AsyncPolkitQuery {
323         sd_bus_message *request, *reply;
324         sd_bus_message_handler_t callback;
325         void *userdata;
326         sd_bus_slot *slot;
327         Hashmap *registry;
328 } AsyncPolkitQuery;
329
330 static void async_polkit_query_free(AsyncPolkitQuery *q) {
331
332         if (!q)
333                 return;
334
335         sd_bus_slot_unref(q->slot);
336
337         if (q->registry && q->request)
338                 hashmap_remove(q->registry, q->request);
339
340         sd_bus_message_unref(q->request);
341         sd_bus_message_unref(q->reply);
342
343         free(q);
344 }
345
346 static int async_polkit_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
347         _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
348         AsyncPolkitQuery *q = userdata;
349         int r;
350
351         assert(reply);
352         assert(q);
353
354         q->slot = sd_bus_slot_unref(q->slot);
355         q->reply = sd_bus_message_ref(reply);
356
357         r = sd_bus_message_rewind(q->request, true);
358         if (r < 0) {
359                 r = sd_bus_reply_method_errno(q->request, r, NULL);
360                 goto finish;
361         }
362
363         r = q->callback(q->request, q->userdata, &error_buffer);
364         r = bus_maybe_reply_error(q->request, r, &error_buffer);
365
366 finish:
367         async_polkit_query_free(q);
368
369         return r;
370 }
371
372 #endif
373
374 int bus_verify_polkit_async(
375                 sd_bus_message *call,
376                 int capability,
377                 const char *action,
378                 const char **details,
379                 bool interactive,
380                 uid_t good_user,
381                 Hashmap **registry,
382                 sd_bus_error *error) {
383
384 #if ENABLE_POLKIT
385         _cleanup_(sd_bus_message_unrefp) sd_bus_message *pk = NULL;
386         AsyncPolkitQuery *q;
387         const char *sender, **k, **v;
388         sd_bus_message_handler_t callback;
389         void *userdata;
390         int c;
391 #endif
392         int r;
393
394         assert(call);
395         assert(action);
396         assert(registry);
397
398         r = check_good_user(call, good_user);
399         if (r != 0)
400                 return r;
401
402 #if ENABLE_POLKIT
403         q = hashmap_get(*registry, call);
404         if (q) {
405                 int authorized, challenge;
406
407                 /* This is the second invocation of this function, and
408                  * there's already a response from polkit, let's
409                  * process it */
410                 assert(q->reply);
411
412                 if (sd_bus_message_is_method_error(q->reply, NULL)) {
413                         const sd_bus_error *e;
414
415                         /* Copy error from polkit reply */
416                         e = sd_bus_message_get_error(q->reply);
417                         sd_bus_error_copy(error, e);
418
419                         /* Treat no PK available as access denied */
420                         if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN))
421                                 return -EACCES;
422
423                         return -sd_bus_error_get_errno(e);
424                 }
425
426                 r = sd_bus_message_enter_container(q->reply, 'r', "bba{ss}");
427                 if (r >= 0)
428                         r = sd_bus_message_read(q->reply, "bb", &authorized, &challenge);
429
430                 if (r < 0)
431                         return r;
432
433                 if (authorized)
434                         return 1;
435
436                 if (challenge)
437                         return sd_bus_error_set(error, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED, "Interactive authentication required.");
438
439                 return -EACCES;
440         }
441 #endif
442
443         r = sd_bus_query_sender_privilege(call, capability);
444         if (r < 0)
445                 return r;
446         else if (r > 0)
447                 return 1;
448
449 #if ENABLE_POLKIT
450         if (sd_bus_get_current_message(call->bus) != call)
451                 return -EINVAL;
452
453         callback = sd_bus_get_current_handler(call->bus);
454         if (!callback)
455                 return -EINVAL;
456
457         userdata = sd_bus_get_current_userdata(call->bus);
458
459         sender = sd_bus_message_get_sender(call);
460         if (!sender)
461                 return -EBADMSG;
462
463         c = sd_bus_message_get_allow_interactive_authorization(call);
464         if (c < 0)
465                 return c;
466         if (c > 0)
467                 interactive = true;
468
469         r = hashmap_ensure_allocated(registry, NULL);
470         if (r < 0)
471                 return r;
472
473         r = sd_bus_message_new_method_call(
474                         call->bus,
475                         &pk,
476                         "org.freedesktop.PolicyKit1",
477                         "/org/freedesktop/PolicyKit1/Authority",
478                         "org.freedesktop.PolicyKit1.Authority",
479                         "CheckAuthorization");
480         if (r < 0)
481                 return r;
482
483         r = sd_bus_message_append(
484                         pk,
485                         "(sa{sv})s",
486                         "system-bus-name", 1, "name", "s", sender,
487                         action);
488         if (r < 0)
489                 return r;
490
491         r = sd_bus_message_open_container(pk, 'a', "{ss}");
492         if (r < 0)
493                 return r;
494
495         STRV_FOREACH_PAIR(k, v, details) {
496                 r = sd_bus_message_append(pk, "{ss}", *k, *v);
497                 if (r < 0)
498                         return r;
499         }
500
501         r = sd_bus_message_close_container(pk);
502         if (r < 0)
503                 return r;
504
505         r = sd_bus_message_append(pk, "us", !!interactive, NULL);
506         if (r < 0)
507                 return r;
508
509         q = new0(AsyncPolkitQuery, 1);
510         if (!q)
511                 return -ENOMEM;
512
513         q->request = sd_bus_message_ref(call);
514         q->callback = callback;
515         q->userdata = userdata;
516
517         r = hashmap_put(*registry, call, q);
518         if (r < 0) {
519                 async_polkit_query_free(q);
520                 return r;
521         }
522
523         q->registry = *registry;
524
525         r = sd_bus_call_async(call->bus, &q->slot, pk, async_polkit_callback, q, 0);
526         if (r < 0) {
527                 async_polkit_query_free(q);
528                 return r;
529         }
530
531         return 0;
532 #endif
533
534         return -EACCES;
535 }
536
537 void bus_verify_polkit_async_registry_free(Hashmap *registry) {
538 #if ENABLE_POLKIT
539         hashmap_free_with_destructor(registry, async_polkit_query_free);
540 #endif
541 }
542
543 #if 0 /// UNNEEDED by elogind
544 int bus_check_peercred(sd_bus *c) {
545         struct ucred ucred;
546         int fd, r;
547
548         assert(c);
549
550         fd = sd_bus_get_fd(c);
551         if (fd < 0)
552                 return fd;
553
554         r = getpeercred(fd, &ucred);
555         if (r < 0)
556                 return r;
557
558         if (ucred.uid != 0 && ucred.uid != geteuid())
559                 return -EPERM;
560
561         return 1;
562 }
563
564 int bus_connect_system_systemd(sd_bus **_bus) {
565         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
566         int r;
567
568         assert(_bus);
569
570         if (geteuid() != 0)
571                 return sd_bus_default_system(_bus);
572
573         /* If we are root then let's talk directly to the system
574          * instance, instead of going via the bus */
575
576         r = sd_bus_new(&bus);
577         if (r < 0)
578                 return r;
579
580         r = sd_bus_set_address(bus, "unix:path=/run/systemd/private");
581         if (r < 0)
582                 return r;
583
584         r = sd_bus_start(bus);
585         if (r < 0)
586                 return sd_bus_default_system(_bus);
587
588         r = bus_check_peercred(bus);
589         if (r < 0)
590                 return r;
591
592         *_bus = TAKE_PTR(bus);
593
594         return 0;
595 }
596
597 int bus_connect_user_systemd(sd_bus **_bus) {
598         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
599         _cleanup_free_ char *ee = NULL;
600         const char *e;
601         int r;
602
603         assert(_bus);
604
605         e = secure_getenv("XDG_RUNTIME_DIR");
606         if (!e)
607                 return sd_bus_default_user(_bus);
608
609         ee = bus_address_escape(e);
610         if (!ee)
611                 return -ENOMEM;
612
613         r = sd_bus_new(&bus);
614         if (r < 0)
615                 return r;
616
617         bus->address = strjoin("unix:path=", ee, "/systemd/private");
618         if (!bus->address)
619                 return -ENOMEM;
620
621         r = sd_bus_start(bus);
622         if (r < 0)
623                 return sd_bus_default_user(_bus);
624
625         r = bus_check_peercred(bus);
626         if (r < 0)
627                 return r;
628
629         *_bus = TAKE_PTR(bus);
630
631         return 0;
632 }
633 #endif // 0
634
635 #define print_property(name, fmt, ...)                                  \
636         do {                                                            \
637                 if (value)                                              \
638                         printf(fmt "\n", __VA_ARGS__);                  \
639                 else                                                    \
640                         printf("%s=" fmt "\n", name, __VA_ARGS__);      \
641         } while (0)
642
643 int bus_print_property(const char *name, sd_bus_message *m, bool value, bool all) {
644         char type;
645         const char *contents;
646         int r;
647
648         assert(name);
649         assert(m);
650
651         r = sd_bus_message_peek_type(m, &type, &contents);
652         if (r < 0)
653                 return r;
654
655         switch (type) {
656
657         case SD_BUS_TYPE_STRING: {
658                 const char *s;
659
660                 r = sd_bus_message_read_basic(m, type, &s);
661                 if (r < 0)
662                         return r;
663
664                 if (all || !isempty(s)) {
665                         bool good;
666
667                         /* This property has a single value, so we need to take
668                          * care not to print a new line, everything else is OK. */
669                         good = !strchr(s, '\n');
670                         print_property(name, "%s", good ? s : "[unprintable]");
671                 }
672
673                 return 1;
674         }
675
676         case SD_BUS_TYPE_BOOLEAN: {
677                 int b;
678
679                 r = sd_bus_message_read_basic(m, type, &b);
680                 if (r < 0)
681                         return r;
682
683                 print_property(name, "%s", yes_no(b));
684
685                 return 1;
686         }
687
688         case SD_BUS_TYPE_UINT64: {
689                 uint64_t u;
690
691                 r = sd_bus_message_read_basic(m, type, &u);
692                 if (r < 0)
693                         return r;
694
695                 /* Yes, heuristics! But we can change this check
696                  * should it turn out to not be sufficient */
697
698                 if (endswith(name, "Timestamp") ||
699                     STR_IN_SET(name, "NextElapseUSecRealtime", "LastTriggerUSec", "TimeUSec", "RTCTimeUSec")) {
700                         char timestamp[FORMAT_TIMESTAMP_MAX];
701                         const char *t;
702
703                         t = format_timestamp(timestamp, sizeof(timestamp), u);
704                         if (t || all)
705                                 print_property(name, "%s", strempty(t));
706
707                 } else if (strstr(name, "USec")) {
708                         char timespan[FORMAT_TIMESPAN_MAX];
709
710                         print_property(name, "%s", format_timespan(timespan, sizeof(timespan), u, 0));
711                 } else if (streq(name, "RestrictNamespaces")) {
712                         _cleanup_free_ char *s = NULL;
713                         const char *result;
714
715                         if ((u & NAMESPACE_FLAGS_ALL) == 0)
716                                 result = "yes";
717                         else if ((u & NAMESPACE_FLAGS_ALL) == NAMESPACE_FLAGS_ALL)
718                                 result = "no";
719                         else {
720                                 r = namespace_flags_to_string(u, &s);
721                                 if (r < 0)
722                                         return r;
723
724                                 result = s;
725                         }
726
727                         print_property(name, "%s", result);
728
729                 } else if (streq(name, "MountFlags")) {
730                         const char *result;
731
732                         result = mount_propagation_flags_to_string(u);
733                         if (!result)
734                                 return -EINVAL;
735
736                         print_property(name, "%s", result);
737
738                 } else if (STR_IN_SET(name, "CapabilityBoundingSet", "AmbientCapabilities")) {
739                         _cleanup_free_ char *s = NULL;
740
741                         r = capability_set_to_string_alloc(u, &s);
742                         if (r < 0)
743                                 return r;
744
745                         print_property(name, "%s", s);
746
747                 } else if ((STR_IN_SET(name, "CPUWeight", "StartupCPUWeight", "IOWeight", "StartupIOWeight") && u == CGROUP_WEIGHT_INVALID) ||
748                            (STR_IN_SET(name, "CPUShares", "StartupCPUShares") && u == CGROUP_CPU_SHARES_INVALID) ||
749                            (STR_IN_SET(name, "BlockIOWeight", "StartupBlockIOWeight") && u == CGROUP_BLKIO_WEIGHT_INVALID) ||
750                            (STR_IN_SET(name, "MemoryCurrent", "TasksCurrent") && u == (uint64_t) -1) ||
751                            (endswith(name, "NSec") && u == (uint64_t) -1))
752
753                         print_property(name, "%s", "[not set]");
754
755                 else if ((STR_IN_SET(name, "MemoryLow", "MemoryHigh", "MemoryMax", "MemorySwapMax", "MemoryLimit") && u == CGROUP_LIMIT_MAX) ||
756                          (STR_IN_SET(name, "TasksMax", "DefaultTasksMax") && u == (uint64_t) -1) ||
757                          (startswith(name, "Limit") && u == (uint64_t) -1) ||
758                          (startswith(name, "DefaultLimit") && u == (uint64_t) -1))
759
760                         print_property(name, "%s", "infinity");
761                 else
762                         print_property(name, "%"PRIu64, u);
763
764                 return 1;
765         }
766
767         case SD_BUS_TYPE_INT64: {
768                 int64_t i;
769
770                 r = sd_bus_message_read_basic(m, type, &i);
771                 if (r < 0)
772                         return r;
773
774                 print_property(name, "%"PRIi64, i);
775
776                 return 1;
777         }
778
779         case SD_BUS_TYPE_UINT32: {
780                 uint32_t u;
781
782                 r = sd_bus_message_read_basic(m, type, &u);
783                 if (r < 0)
784                         return r;
785
786                 if (strstr(name, "UMask") || strstr(name, "Mode"))
787                         print_property(name, "%04o", u);
788                 else if (streq(name, "UID")) {
789                         if (u == UID_INVALID)
790                                 print_property(name, "%s", "[not set]");
791                         else
792                                 print_property(name, "%"PRIu32, u);
793                 } else if (streq(name, "GID")) {
794                         if (u == GID_INVALID)
795                                 print_property(name, "%s", "[not set]");
796                         else
797                                 print_property(name, "%"PRIu32, u);
798                 } else
799                         print_property(name, "%"PRIu32, u);
800
801                 return 1;
802         }
803
804         case SD_BUS_TYPE_INT32: {
805                 int32_t i;
806
807                 r = sd_bus_message_read_basic(m, type, &i);
808                 if (r < 0)
809                         return r;
810
811                 print_property(name, "%"PRIi32, i);
812                 return 1;
813         }
814
815         case SD_BUS_TYPE_DOUBLE: {
816                 double d;
817
818                 r = sd_bus_message_read_basic(m, type, &d);
819                 if (r < 0)
820                         return r;
821
822                 print_property(name, "%g", d);
823                 return 1;
824         }
825
826         case SD_BUS_TYPE_ARRAY:
827                 if (streq(contents, "s")) {
828                         bool first = true;
829                         const char *str;
830
831                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, contents);
832                         if (r < 0)
833                                 return r;
834
835                         while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &str)) > 0) {
836                                 bool good;
837
838                                 if (first && !value)
839                                         printf("%s=", name);
840
841                                 /* This property has multiple space-separated values, so
842                                  * neither spaces nor newlines can be allowed in a value. */
843                                 good = str[strcspn(str, " \n")] == '\0';
844
845                                 printf("%s%s", first ? "" : " ", good ? str : "[unprintable]");
846
847                                 first = false;
848                         }
849                         if (r < 0)
850                                 return r;
851
852                         if (first && all && !value)
853                                 printf("%s=", name);
854                         if (!first || all)
855                                 puts("");
856
857                         r = sd_bus_message_exit_container(m);
858                         if (r < 0)
859                                 return r;
860
861                         return 1;
862
863                 } else if (streq(contents, "y")) {
864                         const uint8_t *u;
865                         size_t n;
866
867                         r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, (const void**) &u, &n);
868                         if (r < 0)
869                                 return r;
870
871                         if (all || n > 0) {
872                                 unsigned int i;
873
874                                 if (!value)
875                                         printf("%s=", name);
876
877                                 for (i = 0; i < n; i++)
878                                         printf("%02x", u[i]);
879
880                                 puts("");
881                         }
882
883                         return 1;
884
885                 } else if (streq(contents, "u")) {
886                         uint32_t *u;
887                         size_t n;
888
889                         r = sd_bus_message_read_array(m, SD_BUS_TYPE_UINT32, (const void**) &u, &n);
890                         if (r < 0)
891                                 return r;
892
893                         if (all || n > 0) {
894                                 unsigned int i;
895
896                                 if (!value)
897                                         printf("%s=", name);
898
899                                 for (i = 0; i < n; i++)
900                                         printf("%08x", u[i]);
901
902                                 puts("");
903                         }
904
905                         return 1;
906                 }
907
908                 break;
909         }
910
911         return 0;
912 }
913
914 int bus_message_print_all_properties(
915                 sd_bus_message *m,
916                 bus_message_print_t func,
917                 char **filter,
918                 bool value,
919                 bool all,
920                 Set **found_properties) {
921
922         int r;
923
924         assert(m);
925
926         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
927         if (r < 0)
928                 return r;
929
930         while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
931                 const char *name;
932                 const char *contents;
933
934                 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &name);
935                 if (r < 0)
936                         return r;
937
938                 if (found_properties) {
939                         r = set_ensure_allocated(found_properties, &string_hash_ops);
940                         if (r < 0)
941                                 return log_oom();
942
943                         r = set_put(*found_properties, name);
944                         if (r < 0 && r != EEXIST)
945                                 return log_oom();
946                 }
947
948                 if (!filter || strv_find(filter, name)) {
949                         r = sd_bus_message_peek_type(m, NULL, &contents);
950                         if (r < 0)
951                                 return r;
952
953                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
954                         if (r < 0)
955                                 return r;
956
957                         if (func)
958                                 r = func(name, m, value, all);
959                         if (!func || r == 0)
960                                 r = bus_print_property(name, m, value, all);
961                         if (r < 0)
962                                 return r;
963                         if (r == 0) {
964                                 if (all)
965                                         printf("%s=[unprintable]\n", name);
966                                 /* skip what we didn't read */
967                                 r = sd_bus_message_skip(m, contents);
968                                 if (r < 0)
969                                         return r;
970                         }
971
972                         r = sd_bus_message_exit_container(m);
973                         if (r < 0)
974                                 return r;
975                 } else {
976                         r = sd_bus_message_skip(m, "v");
977                         if (r < 0)
978                                 return r;
979                 }
980
981                 r = sd_bus_message_exit_container(m);
982                 if (r < 0)
983                         return r;
984         }
985         if (r < 0)
986                 return r;
987
988         r = sd_bus_message_exit_container(m);
989         if (r < 0)
990                 return r;
991
992         return 0;
993 }
994
995 int bus_print_all_properties(
996                 sd_bus *bus,
997                 const char *dest,
998                 const char *path,
999                 bus_message_print_t func,
1000                 char **filter,
1001                 bool value,
1002                 bool all,
1003                 Set **found_properties) {
1004
1005         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1006         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1007         int r;
1008
1009         assert(bus);
1010         assert(path);
1011
1012         r = sd_bus_call_method(bus,
1013                         dest,
1014                         path,
1015                         "org.freedesktop.DBus.Properties",
1016                         "GetAll",
1017                         &error,
1018                         &reply,
1019                         "s", "");
1020         if (r < 0)
1021                 return r;
1022
1023         return bus_message_print_all_properties(reply, func, filter, value, all, found_properties);
1024 }
1025
1026 int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1027         sd_id128_t *p = userdata;
1028         const void *v;
1029         size_t n;
1030         int r;
1031
1032         r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n);
1033         if (r < 0)
1034                 return r;
1035
1036         if (n == 0)
1037                 *p = SD_ID128_NULL;
1038         else if (n == 16)
1039                 memcpy((*p).bytes, v, n);
1040         else
1041                 return -EINVAL;
1042
1043         return 0;
1044 }
1045
1046 static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, unsigned flags, sd_bus_error *error, void *userdata) {
1047         char type;
1048         int r;
1049
1050         r = sd_bus_message_peek_type(m, &type, NULL);
1051         if (r < 0)
1052                 return r;
1053
1054         switch (type) {
1055
1056         case SD_BUS_TYPE_STRING: {
1057                 const char **p = userdata;
1058                 const char *s;
1059
1060                 r = sd_bus_message_read_basic(m, type, &s);
1061                 if (r < 0)
1062                         return r;
1063
1064                 if (isempty(s))
1065                         s = NULL;
1066
1067                 if (flags & BUS_MAP_STRDUP)
1068                         return free_and_strdup((char **) userdata, s);
1069
1070                 *p = s;
1071                 return 0;
1072         }
1073
1074         case SD_BUS_TYPE_ARRAY: {
1075                 _cleanup_strv_free_ char **l = NULL;
1076                 char ***p = userdata;
1077
1078                 r = bus_message_read_strv_extend(m, &l);
1079                 if (r < 0)
1080                         return r;
1081
1082                 return strv_free_and_replace(*p, l);
1083         }
1084
1085         case SD_BUS_TYPE_BOOLEAN: {
1086                 int b;
1087
1088                 r = sd_bus_message_read_basic(m, type, &b);
1089                 if (r < 0)
1090                         return r;
1091
1092                 if (flags & BUS_MAP_BOOLEAN_AS_BOOL)
1093                         *(bool*) userdata = b;
1094                 else
1095                         *(int*) userdata = b;
1096
1097                 return 0;
1098         }
1099
1100         case SD_BUS_TYPE_INT32:
1101         case SD_BUS_TYPE_UINT32: {
1102                 uint32_t u, *p = userdata;
1103
1104                 r = sd_bus_message_read_basic(m, type, &u);
1105                 if (r < 0)
1106                         return r;
1107
1108                 *p = u;
1109                 return 0;
1110         }
1111
1112         case SD_BUS_TYPE_INT64:
1113         case SD_BUS_TYPE_UINT64: {
1114                 uint64_t t, *p = userdata;
1115
1116                 r = sd_bus_message_read_basic(m, type, &t);
1117                 if (r < 0)
1118                         return r;
1119
1120                 *p = t;
1121                 return 0;
1122         }
1123
1124         case SD_BUS_TYPE_DOUBLE: {
1125                 double d, *p = userdata;
1126
1127                 r = sd_bus_message_read_basic(m, type, &d);
1128                 if (r < 0)
1129                         return r;
1130
1131                 *p = d;
1132                 return 0;
1133         }}
1134
1135         return -EOPNOTSUPP;
1136 }
1137
1138 int bus_message_map_all_properties(
1139                 sd_bus_message *m,
1140                 const struct bus_properties_map *map,
1141                 unsigned flags,
1142                 sd_bus_error *error,
1143                 void *userdata) {
1144
1145         int r;
1146
1147         assert(m);
1148         assert(map);
1149
1150         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
1151         if (r < 0)
1152                 return r;
1153
1154         while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1155                 const struct bus_properties_map *prop;
1156                 const char *member;
1157                 const char *contents;
1158                 void *v;
1159                 unsigned i;
1160
1161                 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
1162                 if (r < 0)
1163                         return r;
1164
1165                 for (i = 0, prop = NULL; map[i].member; i++)
1166                         if (streq(map[i].member, member)) {
1167                                 prop = &map[i];
1168                                 break;
1169                         }
1170
1171                 if (prop) {
1172                         r = sd_bus_message_peek_type(m, NULL, &contents);
1173                         if (r < 0)
1174                                 return r;
1175
1176                         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
1177                         if (r < 0)
1178                                 return r;
1179
1180                         v = (uint8_t *)userdata + prop->offset;
1181                         if (map[i].set)
1182                                 r = prop->set(sd_bus_message_get_bus(m), member, m, error, v);
1183                         else
1184                                 r = map_basic(sd_bus_message_get_bus(m), member, m, flags, error, v);
1185                         if (r < 0)
1186                                 return r;
1187
1188                         r = sd_bus_message_exit_container(m);
1189                         if (r < 0)
1190                                 return r;
1191                 } else {
1192                         r = sd_bus_message_skip(m, "v");
1193                         if (r < 0)
1194                                 return r;
1195                 }
1196
1197                 r = sd_bus_message_exit_container(m);
1198                 if (r < 0)
1199                         return r;
1200         }
1201         if (r < 0)
1202                 return r;
1203
1204         return sd_bus_message_exit_container(m);
1205 }
1206
1207 #if 0 /// UNNEEDED by elogind
1208 int bus_message_map_properties_changed(
1209                 sd_bus_message *m,
1210                 const struct bus_properties_map *map,
1211                 unsigned flags,
1212                 sd_bus_error *error,
1213                 void *userdata) {
1214
1215         const char *member;
1216         int r, invalidated, i;
1217
1218         assert(m);
1219         assert(map);
1220
1221         r = bus_message_map_all_properties(m, map, flags, error, userdata);
1222         if (r < 0)
1223                 return r;
1224
1225         r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s");
1226         if (r < 0)
1227                 return r;
1228
1229         invalidated = 0;
1230         while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0)
1231                 for (i = 0; map[i].member; i++)
1232                         if (streq(map[i].member, member)) {
1233                                 ++invalidated;
1234                                 break;
1235                         }
1236         if (r < 0)
1237                 return r;
1238
1239         r = sd_bus_message_exit_container(m);
1240         if (r < 0)
1241                 return r;
1242
1243         return invalidated;
1244 }
1245 #endif // 0
1246
1247 int bus_map_all_properties(
1248                 sd_bus *bus,
1249                 const char *destination,
1250                 const char *path,
1251                 const struct bus_properties_map *map,
1252                 unsigned flags,
1253                 sd_bus_error *error,
1254                 sd_bus_message **reply,
1255                 void *userdata) {
1256
1257         _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1258         int r;
1259
1260         assert(bus);
1261         assert(destination);
1262         assert(path);
1263         assert(map);
1264         assert(reply || (flags & BUS_MAP_STRDUP));
1265
1266         r = sd_bus_call_method(
1267                         bus,
1268                         destination,
1269                         path,
1270                         "org.freedesktop.DBus.Properties",
1271                         "GetAll",
1272                         error,
1273                         &m,
1274                         "s", "");
1275         if (r < 0)
1276                 return r;
1277
1278         r = bus_message_map_all_properties(m, map, flags, error, userdata);
1279         if (r < 0)
1280                 return r;
1281
1282         if (reply)
1283                 *reply = sd_bus_message_ref(m);
1284
1285         return r;
1286 }
1287
1288 int bus_connect_transport(BusTransport transport, const char *host, bool user, sd_bus **ret) {
1289         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1290         int r;
1291
1292         assert(transport >= 0);
1293         assert(transport < _BUS_TRANSPORT_MAX);
1294         assert(ret);
1295
1296         assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1297         assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1298
1299         switch (transport) {
1300
1301         case BUS_TRANSPORT_LOCAL:
1302 #if 0 /// elogind does not support a user bus
1303                 if (user)
1304                         r = sd_bus_default_user(&bus);
1305 #endif // 0
1306                 else {
1307                         if (sd_booted() <= 0) {
1308                                 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1309                                 log_error("System has not been booted with elogind as init system (PID 1). Can't operate.");
1310
1311                                 return -EHOSTDOWN;
1312                         }
1313                         r = sd_bus_default_system(&bus);
1314                 }
1315                 break;
1316
1317         case BUS_TRANSPORT_REMOTE:
1318                 r = sd_bus_open_system_remote(&bus, host);
1319                 break;
1320
1321         case BUS_TRANSPORT_MACHINE:
1322                 r = sd_bus_open_system_machine(&bus, host);
1323                 break;
1324
1325         default:
1326                 assert_not_reached("Hmm, unknown transport type.");
1327         }
1328         if (r < 0)
1329                 return r;
1330
1331         r = sd_bus_set_exit_on_disconnect(bus, true);
1332         if (r < 0)
1333                 return r;
1334
1335         *ret = TAKE_PTR(bus);
1336
1337         return 0;
1338 }
1339
1340 #if 0 /// UNNEEDED by elogind
1341 int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1342         int r;
1343
1344         assert(transport >= 0);
1345         assert(transport < _BUS_TRANSPORT_MAX);
1346         assert(bus);
1347
1348         assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1349         assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1350
1351         switch (transport) {
1352
1353         case BUS_TRANSPORT_LOCAL:
1354                 if (user)
1355                         r = bus_connect_user_systemd(bus);
1356                 else {
1357                         if (sd_booted() <= 0) {
1358                                 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1359                                 log_error("System has not been booted with systemd as init system (PID 1). Can't operate.");
1360
1361                                 return -EHOSTDOWN;
1362                         }
1363                         r = bus_connect_system_systemd(bus);
1364                 }
1365                 break;
1366
1367         case BUS_TRANSPORT_REMOTE:
1368                 r = sd_bus_open_system_remote(bus, host);
1369                 break;
1370
1371         case BUS_TRANSPORT_MACHINE:
1372                 r = sd_bus_open_system_machine(bus, host);
1373                 break;
1374
1375         default:
1376                 assert_not_reached("Hmm, unknown transport type.");
1377         }
1378
1379         return r;
1380 }
1381 #endif // 0
1382
1383 int bus_property_get_bool(
1384                 sd_bus *bus,
1385                 const char *path,
1386                 const char *interface,
1387                 const char *property,
1388                 sd_bus_message *reply,
1389                 void *userdata,
1390                 sd_bus_error *error) {
1391
1392         int b = *(bool*) userdata;
1393
1394         return sd_bus_message_append_basic(reply, 'b', &b);
1395 }
1396
1397 int bus_property_set_bool(
1398                 sd_bus *bus,
1399                 const char *path,
1400                 const char *interface,
1401                 const char *property,
1402                 sd_bus_message *value,
1403                 void *userdata,
1404                 sd_bus_error *error) {
1405
1406         int b, r;
1407
1408         r = sd_bus_message_read(value, "b", &b);
1409         if (r < 0)
1410                 return r;
1411
1412         *(bool*) userdata = b;
1413         return 0;
1414 }
1415
1416 #if 0 /// UNNEEDED by elogind
1417 int bus_property_get_id128(
1418                 sd_bus *bus,
1419                 const char *path,
1420                 const char *interface,
1421                 const char *property,
1422                 sd_bus_message *reply,
1423                 void *userdata,
1424                 sd_bus_error *error) {
1425
1426         sd_id128_t *id = userdata;
1427
1428         if (sd_id128_is_null(*id)) /* Add an empty array if the ID is zero */
1429                 return sd_bus_message_append(reply, "ay", 0);
1430         else
1431                 return sd_bus_message_append_array(reply, 'y', id->bytes, 16);
1432 }
1433 #endif // 0
1434
1435 #if __SIZEOF_SIZE_T__ != 8
1436 int bus_property_get_size(
1437                 sd_bus *bus,
1438                 const char *path,
1439                 const char *interface,
1440                 const char *property,
1441                 sd_bus_message *reply,
1442                 void *userdata,
1443                 sd_bus_error *error) {
1444
1445         uint64_t sz = *(size_t*) userdata;
1446
1447         return sd_bus_message_append_basic(reply, 't', &sz);
1448 }
1449 #endif
1450
1451 #if __SIZEOF_LONG__ != 8
1452 int bus_property_get_long(
1453                 sd_bus *bus,
1454                 const char *path,
1455                 const char *interface,
1456                 const char *property,
1457                 sd_bus_message *reply,
1458                 void *userdata,
1459                 sd_bus_error *error) {
1460
1461         int64_t l = *(long*) userdata;
1462
1463         return sd_bus_message_append_basic(reply, 'x', &l);
1464 }
1465
1466 int bus_property_get_ulong(
1467                 sd_bus *bus,
1468                 const char *path,
1469                 const char *interface,
1470                 const char *property,
1471                 sd_bus_message *reply,
1472                 void *userdata,
1473                 sd_bus_error *error) {
1474
1475         uint64_t ul = *(unsigned long*) userdata;
1476
1477         return sd_bus_message_append_basic(reply, 't', &ul);
1478 }
1479 #endif
1480
1481 int bus_log_parse_error(int r) {
1482         return log_error_errno(r, "Failed to parse bus message: %m");
1483 }
1484
1485 #if 0 /// UNNEEDED by elogind
1486 int bus_log_create_error(int r) {
1487         return log_error_errno(r, "Failed to create bus message: %m");
1488 }
1489
1490 #endif // 0
1491 #if 0 /// UNNEEDED by elogind
1492 /**
1493  * bus_path_encode_unique() - encode unique object path
1494  * @b: bus connection or NULL
1495  * @prefix: object path prefix
1496  * @sender_id: unique-name of client, or NULL
1497  * @external_id: external ID to be chosen by client, or NULL
1498  * @ret_path: storage for encoded object path pointer
1499  *
1500  * Whenever we provide a bus API that allows clients to create and manage
1501  * server-side objects, we need to provide a unique name for these objects. If
1502  * we let the server choose the name, we suffer from a race condition: If a
1503  * client creates an object asynchronously, it cannot destroy that object until
1504  * it received the method reply. It cannot know the name of the new object,
1505  * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
1506  *
1507  * Therefore, many APIs allow the client to choose the unique name for newly
1508  * created objects. There're two problems to solve, though:
1509  *    1) Object names are usually defined via dbus object paths, which are
1510  *       usually globally namespaced. Therefore, multiple clients must be able
1511  *       to choose unique object names without interference.
1512  *    2) If multiple libraries share the same bus connection, they must be
1513  *       able to choose unique object names without interference.
1514  * The first problem is solved easily by prefixing a name with the
1515  * unique-bus-name of a connection. The server side must enforce this and
1516  * reject any other name. The second problem is solved by providing unique
1517  * suffixes from within sd-bus.
1518  *
1519  * This helper allows clients to create unique object-paths. It uses the
1520  * template '/prefix/sender_id/external_id' and returns the new path in
1521  * @ret_path (must be freed by the caller).
1522  * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
1523  * NULL, this function allocates a unique suffix via @b (by requesting a new
1524  * cookie). If both @sender_id and @external_id are given, @b can be passed as
1525  * NULL.
1526  *
1527  * Returns: 0 on success, negative error code on failure.
1528  */
1529 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
1530         _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
1531         char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
1532         int r;
1533
1534         assert_return(b || (sender_id && external_id), -EINVAL);
1535         assert_return(object_path_is_valid(prefix), -EINVAL);
1536         assert_return(ret_path, -EINVAL);
1537
1538         if (!sender_id) {
1539                 r = sd_bus_get_unique_name(b, &sender_id);
1540                 if (r < 0)
1541                         return r;
1542         }
1543
1544         if (!external_id) {
1545                 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
1546                 external_id = external_buf;
1547         }
1548
1549         sender_label = bus_label_escape(sender_id);
1550         if (!sender_label)
1551                 return -ENOMEM;
1552
1553         external_label = bus_label_escape(external_id);
1554         if (!external_label)
1555                 return -ENOMEM;
1556
1557         p = strjoin(prefix, "/", sender_label, "/", external_label);
1558         if (!p)
1559                 return -ENOMEM;
1560
1561         *ret_path = p;
1562         return 0;
1563 }
1564
1565 /**
1566  * bus_path_decode_unique() - decode unique object path
1567  * @path: object path to decode
1568  * @prefix: object path prefix
1569  * @ret_sender: output parameter for sender-id label
1570  * @ret_external: output parameter for external-id label
1571  *
1572  * This does the reverse of bus_path_encode_unique() (see its description for
1573  * details). Both trailing labels, sender-id and external-id, are unescaped and
1574  * returned in the given output parameters (the caller must free them).
1575  *
1576  * Note that this function returns 0 if the path does not match the template
1577  * (see bus_path_encode_unique()), 1 if it matched.
1578  *
1579  * Returns: Negative error code on failure, 0 if the given object path does not
1580  *          match the template (return parameters are set to NULL), 1 if it was
1581  *          parsed successfully (return parameters contain allocated labels).
1582  */
1583 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
1584         const char *p, *q;
1585         char *sender, *external;
1586
1587         assert(object_path_is_valid(path));
1588         assert(object_path_is_valid(prefix));
1589         assert(ret_sender);
1590         assert(ret_external);
1591
1592         p = object_path_startswith(path, prefix);
1593         if (!p) {
1594                 *ret_sender = NULL;
1595                 *ret_external = NULL;
1596                 return 0;
1597         }
1598
1599         q = strchr(p, '/');
1600         if (!q) {
1601                 *ret_sender = NULL;
1602                 *ret_external = NULL;
1603                 return 0;
1604         }
1605
1606         sender = bus_label_unescape_n(p, q - p);
1607         external = bus_label_unescape(q + 1);
1608         if (!sender || !external) {
1609                 free(sender);
1610                 free(external);
1611                 return -ENOMEM;
1612         }
1613
1614         *ret_sender = sender;
1615         *ret_external = external;
1616         return 1;
1617 }
1618 #endif // 0
1619
1620 #if 0 /// UNNEEDED by elogind
1621 int bus_property_get_rlimit(
1622                 sd_bus *bus,
1623                 const char *path,
1624                 const char *interface,
1625                 const char *property,
1626                 sd_bus_message *reply,
1627                 void *userdata,
1628                 sd_bus_error *error) {
1629
1630         const char *is_soft;
1631         struct rlimit *rl;
1632         uint64_t u;
1633         rlim_t x;
1634
1635         assert(bus);
1636         assert(reply);
1637         assert(userdata);
1638
1639         is_soft = endswith(property, "Soft");
1640
1641         rl = *(struct rlimit**) userdata;
1642         if (rl)
1643                 x = is_soft ? rl->rlim_cur : rl->rlim_max;
1644         else {
1645                 struct rlimit buf = {};
1646                 const char *s, *p;
1647                 int z;
1648
1649                 /* Chop off "Soft" suffix */
1650                 s = is_soft ? strndupa(property, is_soft - property) : property;
1651
1652                 /* Skip over any prefix, such as "Default" */
1653                 assert_se(p = strstr(s, "Limit"));
1654
1655                 z = rlimit_from_string(p + 5);
1656                 assert(z >= 0);
1657
1658                 (void) getrlimit(z, &buf);
1659                 x = is_soft ? buf.rlim_cur : buf.rlim_max;
1660         }
1661
1662         /* rlim_t might have different sizes, let's map RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on all
1663          * archs */
1664         u = x == RLIM_INFINITY ? (uint64_t) -1 : (uint64_t) x;
1665
1666         return sd_bus_message_append(reply, "t", u);
1667 }
1668
1669 int bus_track_add_name_many(sd_bus_track *t, char **l) {
1670         int r = 0;
1671         char **i;
1672
1673         assert(t);
1674
1675         /* Continues adding after failure, and returns the first failure. */
1676
1677         STRV_FOREACH(i, l) {
1678                 int k;
1679
1680                 k = sd_bus_track_add_name(t, *i);
1681                 if (k < 0 && r >= 0)
1682                         r = k;
1683         }
1684
1685         return r;
1686 }
1687 #endif // 0
1688
1689 int bus_open_system_watch_bind_with_description(sd_bus **ret, const char *description) {
1690         _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1691         const char *e;
1692         int r;
1693
1694         assert(ret);
1695
1696         /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal turned on. */
1697
1698         r = sd_bus_new(&bus);
1699         if (r < 0)
1700                 return r;
1701
1702         if (description) {
1703                 r = sd_bus_set_description(bus, description);
1704                 if (r < 0)
1705                         return r;
1706         }
1707
1708         e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1709         if (!e)
1710                 e = DEFAULT_SYSTEM_BUS_ADDRESS;
1711
1712         r = sd_bus_set_address(bus, e);
1713         if (r < 0)
1714                 return r;
1715
1716         r = sd_bus_set_bus_client(bus, true);
1717         if (r < 0)
1718                 return r;
1719
1720         r = sd_bus_set_trusted(bus, true);
1721         if (r < 0)
1722                 return r;
1723
1724         r = sd_bus_negotiate_creds(bus, true, SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_EFFECTIVE_CAPS);
1725         if (r < 0)
1726                 return r;
1727
1728         r = sd_bus_set_watch_bind(bus, true);
1729         if (r < 0)
1730                 return r;
1731
1732         r = sd_bus_set_connected_signal(bus, true);
1733         if (r < 0)
1734                 return r;
1735
1736         r = sd_bus_start(bus);
1737         if (r < 0)
1738                 return r;
1739
1740         *ret = TAKE_PTR(bus);
1741
1742         return 0;
1743 }
1744
1745 struct request_name_data {
1746         unsigned n_ref;
1747
1748         const char *name;
1749         uint64_t flags;
1750         void *userdata;
1751 };
1752
1753 static void request_name_destroy_callback(void *userdata) {
1754         struct request_name_data *data = userdata;
1755
1756         assert(data);
1757         assert(data->n_ref > 0);
1758
1759         log_info("%s n_ref=%u", __func__, data->n_ref);
1760
1761         data->n_ref--;
1762         if (data->n_ref == 0)
1763                 free(data);
1764 }
1765
1766 static int reload_dbus_handler(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1767         struct request_name_data *data = userdata;
1768         const sd_bus_error *e;
1769         int r;
1770
1771         assert(data);
1772         assert(data->name);
1773         assert(data->n_ref > 0);
1774
1775         e = sd_bus_message_get_error(m);
1776         if (e) {
1777                 log_error_errno(sd_bus_error_get_errno(e), "Failed to reload DBus configuration: %s", e->message);
1778                 return 1;
1779         }
1780
1781         /* Here, use the default request name handler to avoid an infinite loop of reloading and requesting. */
1782         r = sd_bus_request_name_async(sd_bus_message_get_bus(m), NULL, data->name, data->flags, NULL, data->userdata);
1783         if (r < 0)
1784                 log_error_errno(r, "Failed to request name: %m");
1785
1786         return 1;
1787 }
1788
1789 static int request_name_handler_may_reload_dbus(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1790         struct request_name_data *data = userdata;
1791         uint32_t ret;
1792         int r;
1793
1794         assert(m);
1795         assert(data);
1796
1797         if (sd_bus_message_is_method_error(m, NULL)) {
1798                 const sd_bus_error *e = sd_bus_message_get_error(m);
1799                 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1800
1801                 if (!sd_bus_error_has_name(e, SD_BUS_ERROR_ACCESS_DENIED)) {
1802                         log_debug_errno(sd_bus_error_get_errno(e),
1803                                         "Unable to request name, failing connection: %s",
1804                                         e->message);
1805
1806                         bus_enter_closing(sd_bus_message_get_bus(m));
1807                         return 1;
1808                 }
1809
1810                 log_debug_errno(sd_bus_error_get_errno(e),
1811                                 "Unable to request name, will retry after reloading DBus configuration: %s",
1812                                 e->message);
1813
1814                 /* If systemd-timesyncd.service enables DynamicUser= and dbus.service
1815                  * started before the dynamic user is realized, then the DBus policy
1816                  * about timesyncd has not been enabled yet. So, let's try to reload
1817                  * DBus configuration, and after that request the name again. Note that it
1818                  * seems that no privileges are necessary to call the following method. */
1819
1820                 r = sd_bus_call_method_async(
1821                                 sd_bus_message_get_bus(m),
1822                                 &slot,
1823                                 "org.freedesktop.DBus",
1824                                 "/org/freedesktop/DBus",
1825                                 "org.freedesktop.DBus",
1826                                 "ReloadConfig",
1827                                 reload_dbus_handler,
1828                                 data, NULL);
1829                 if (r < 0) {
1830                         log_error_errno(r, "Failed to reload DBus configuration: %m");
1831                         bus_enter_closing(sd_bus_message_get_bus(m));
1832                         return 1;
1833                 }
1834
1835                 data->n_ref ++;
1836                 assert_se(sd_bus_slot_set_destroy_callback(slot, request_name_destroy_callback) >= 0);
1837
1838                 r = sd_bus_slot_set_floating(slot, true);
1839                 if (r < 0)
1840                         return r;
1841
1842                 return 1;
1843         }
1844
1845         r = sd_bus_message_read(m, "u", &ret);
1846         if (r < 0)
1847                 return r;
1848
1849         switch (ret) {
1850
1851         case BUS_NAME_ALREADY_OWNER:
1852                 log_debug("Already owner of requested service name, ignoring.");
1853                 return 1;
1854
1855         case BUS_NAME_IN_QUEUE:
1856                 log_debug("In queue for requested service name.");
1857                 return 1;
1858
1859         case BUS_NAME_PRIMARY_OWNER:
1860                 log_debug("Successfully acquired requested service name.");
1861                 return 1;
1862
1863         case BUS_NAME_EXISTS:
1864                 log_debug("Requested service name already owned, failing connection.");
1865                 bus_enter_closing(sd_bus_message_get_bus(m));
1866                 return 1;
1867         }
1868
1869         log_debug("Unexpected response from RequestName(), failing connection.");
1870         bus_enter_closing(sd_bus_message_get_bus(m));
1871         return 1;
1872 }
1873
1874 int bus_request_name_async_may_reload_dbus(sd_bus *bus, sd_bus_slot **ret_slot, const char *name, uint64_t flags, void *userdata) {
1875         _cleanup_free_ struct request_name_data *data = NULL;
1876         _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1877         int r;
1878
1879         data = new(struct request_name_data, 1);
1880         if (!data)
1881                 return -ENOMEM;
1882
1883         *data = (struct request_name_data) {
1884                 .n_ref = 1,
1885                 .name = name,
1886                 .flags = flags,
1887                 .userdata = userdata,
1888         };
1889
1890         r = sd_bus_request_name_async(bus, &slot, name, flags, request_name_handler_may_reload_dbus, data);
1891         if (r < 0)
1892                 return r;
1893
1894         assert_se(sd_bus_slot_set_destroy_callback(slot, request_name_destroy_callback) >= 0);
1895         TAKE_PTR(data);
1896
1897         if (ret_slot)
1898                 *ret_slot = TAKE_PTR(slot);
1899         else {
1900                 r = sd_bus_slot_set_floating(slot, true);
1901                 if (r < 0)
1902                         return r;
1903         }
1904
1905         return 0;
1906 }
1907
1908 int bus_reply_pair_array(sd_bus_message *m, char **l) {
1909         _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1910         char **k, **v;
1911         int r;
1912
1913         assert(m);
1914
1915         /* Reply to the specified message with a message containing a dictionary put together from the specified
1916          * strv */
1917
1918         r = sd_bus_message_new_method_return(m, &reply);
1919         if (r < 0)
1920                 return r;
1921
1922         r = sd_bus_message_open_container(reply, 'a', "{ss}");
1923         if (r < 0)
1924                 return r;
1925
1926         STRV_FOREACH_PAIR(k, v, l) {
1927                 r = sd_bus_message_append(reply, "{ss}", *k, *v);
1928                 if (r < 0)
1929                         return r;
1930         }
1931
1932         r = sd_bus_message_close_container(reply);
1933         if (r < 0)
1934                 return r;
1935
1936         return sd_bus_send(NULL, reply, NULL);
1937 }