1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2013 Lennart Poettering
14 #include <sys/ioctl.h>
15 #include <sys/resource.h>
16 #include <sys/socket.h>
19 #include "sd-bus-protocol.h"
21 #include "sd-daemon.h"
25 #include "alloc-util.h"
26 #include "bus-internal.h"
27 #include "bus-label.h"
28 #include "bus-message.h"
31 #include "cgroup-util.h"
36 #include "mount-util.h"
38 #include "parse-util.h"
39 #include "proc-cmdline.h"
40 //#include "rlimit-util.h"
41 #include "stdio-util.h"
43 #include "user-util.h"
45 #if 0 /// UNNEEDED by elogind
46 static int name_owner_change_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
47 sd_event *e = userdata;
52 sd_bus_close(sd_bus_message_get_bus(m));
58 int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name) {
67 /* We unregister the name here and then wait for the
68 * NameOwnerChanged signal for this event to arrive before we
69 * quit. We do this in order to make sure that any queued
70 * requests are still processed before we really exit. */
72 r = sd_bus_get_unique_name(bus, &unique);
77 "sender='org.freedesktop.DBus',"
79 "interface='org.freedesktop.DBus',"
80 "member='NameOwnerChanged',"
81 "path='/org/freedesktop/DBus',"
83 "arg1='", unique, "',",
86 r = sd_bus_add_match_async(bus, NULL, match, name_owner_change_callback, NULL, e);
90 r = sd_bus_release_name_async(bus, NULL, name, NULL, NULL);
97 int bus_event_loop_with_idle(
102 check_idle_t check_idle,
104 bool exiting = false;
114 r = sd_event_get_state(e);
117 if (r == SD_EVENT_FINISHED)
121 idle = check_idle(userdata);
125 r = sd_event_run(e, exiting || !idle ? (uint64_t) -1 : timeout);
129 if (r == 0 && !exiting && idle) {
131 r = sd_bus_try_close(bus);
135 /* Fallback for dbus1 connections: we
136 * unregister the name and wait for the
137 * response to come through for it */
138 if (r == -EOPNOTSUPP) {
140 /* Inform the service manager that we
141 * are going down, so that it will
142 * queue all further start requests,
143 * instead of assuming we are already
145 sd_notify(false, "STOPPING=1");
147 r = bus_async_unregister_and_exit(e, bus, name);
163 r = sd_event_get_exit_code(e, &code);
171 int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error) {
172 _cleanup_(sd_bus_message_unrefp) sd_bus_message *rep = NULL;
173 int r, has_owner = 0;
178 r = sd_bus_call_method(c,
179 "org.freedesktop.DBus",
180 "/org/freedesktop/dbus",
181 "org.freedesktop.DBus",
190 r = sd_bus_message_read_basic(rep, 'b', &has_owner);
192 return sd_bus_error_set_errno(error, r);
197 static int check_good_user(sd_bus_message *m, uid_t good_user) {
198 _cleanup_(sd_bus_creds_unrefp) sd_bus_creds *creds = NULL;
204 if (good_user == UID_INVALID)
207 r = sd_bus_query_sender_creds(m, SD_BUS_CREDS_EUID, &creds);
211 /* Don't trust augmented credentials for authorization */
212 assert_return((sd_bus_creds_get_augmented_mask(creds) & SD_BUS_CREDS_EUID) == 0, -EPERM);
214 r = sd_bus_creds_get_euid(creds, &sender_uid);
218 return sender_uid == good_user;
222 sd_bus_message *call,
225 const char **details,
235 /* Tests non-interactively! */
237 r = check_good_user(call, good_user);
241 r = sd_bus_query_sender_privilege(call, capability);
248 _cleanup_(sd_bus_message_unrefp) sd_bus_message *request = NULL;
249 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
250 int authorized = false, challenge = false;
251 const char *sender, **k, **v;
253 sender = sd_bus_message_get_sender(call);
257 r = sd_bus_message_new_method_call(
260 "org.freedesktop.PolicyKit1",
261 "/org/freedesktop/PolicyKit1/Authority",
262 "org.freedesktop.PolicyKit1.Authority",
263 "CheckAuthorization");
267 r = sd_bus_message_append(
270 "system-bus-name", 1, "name", "s", sender,
275 r = sd_bus_message_open_container(request, 'a', "{ss}");
279 STRV_FOREACH_PAIR(k, v, details) {
280 r = sd_bus_message_append(request, "{ss}", *k, *v);
285 r = sd_bus_message_close_container(request);
289 r = sd_bus_message_append(request, "us", 0, NULL);
293 r = sd_bus_call(call->bus, request, 0, e, &reply);
295 /* Treat no PK available as access denied */
296 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN)) {
297 sd_bus_error_free(e);
304 r = sd_bus_message_enter_container(reply, 'r', "bba{ss}");
308 r = sd_bus_message_read(reply, "bb", &authorized, &challenge);
316 *_challenge = challenge;
327 typedef struct AsyncPolkitQuery {
328 sd_bus_message *request, *reply;
329 sd_bus_message_handler_t callback;
335 static void async_polkit_query_free(AsyncPolkitQuery *q) {
340 sd_bus_slot_unref(q->slot);
342 if (q->registry && q->request)
343 hashmap_remove(q->registry, q->request);
345 sd_bus_message_unref(q->request);
346 sd_bus_message_unref(q->reply);
351 static int async_polkit_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
352 _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
353 AsyncPolkitQuery *q = userdata;
359 q->slot = sd_bus_slot_unref(q->slot);
360 q->reply = sd_bus_message_ref(reply);
362 r = sd_bus_message_rewind(q->request, true);
364 r = sd_bus_reply_method_errno(q->request, r, NULL);
368 r = q->callback(q->request, q->userdata, &error_buffer);
369 r = bus_maybe_reply_error(q->request, r, &error_buffer);
372 async_polkit_query_free(q);
379 int bus_verify_polkit_async(
380 sd_bus_message *call,
383 const char **details,
387 sd_bus_error *error) {
390 _cleanup_(sd_bus_message_unrefp) sd_bus_message *pk = NULL;
392 const char *sender, **k, **v;
393 sd_bus_message_handler_t callback;
403 r = check_good_user(call, good_user);
408 q = hashmap_get(*registry, call);
410 int authorized, challenge;
412 /* This is the second invocation of this function, and
413 * there's already a response from polkit, let's
417 if (sd_bus_message_is_method_error(q->reply, NULL)) {
418 const sd_bus_error *e;
420 /* Copy error from polkit reply */
421 e = sd_bus_message_get_error(q->reply);
422 sd_bus_error_copy(error, e);
424 /* Treat no PK available as access denied */
425 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN))
428 return -sd_bus_error_get_errno(e);
431 r = sd_bus_message_enter_container(q->reply, 'r', "bba{ss}");
433 r = sd_bus_message_read(q->reply, "bb", &authorized, &challenge);
442 return sd_bus_error_set(error, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED, "Interactive authentication required.");
448 r = sd_bus_query_sender_privilege(call, capability);
455 if (sd_bus_get_current_message(call->bus) != call)
458 callback = sd_bus_get_current_handler(call->bus);
462 userdata = sd_bus_get_current_userdata(call->bus);
464 sender = sd_bus_message_get_sender(call);
468 c = sd_bus_message_get_allow_interactive_authorization(call);
474 r = hashmap_ensure_allocated(registry, NULL);
478 r = sd_bus_message_new_method_call(
481 "org.freedesktop.PolicyKit1",
482 "/org/freedesktop/PolicyKit1/Authority",
483 "org.freedesktop.PolicyKit1.Authority",
484 "CheckAuthorization");
488 r = sd_bus_message_append(
491 "system-bus-name", 1, "name", "s", sender,
496 r = sd_bus_message_open_container(pk, 'a', "{ss}");
500 STRV_FOREACH_PAIR(k, v, details) {
501 r = sd_bus_message_append(pk, "{ss}", *k, *v);
506 r = sd_bus_message_close_container(pk);
510 r = sd_bus_message_append(pk, "us", !!interactive, NULL);
514 q = new0(AsyncPolkitQuery, 1);
518 q->request = sd_bus_message_ref(call);
519 q->callback = callback;
520 q->userdata = userdata;
522 r = hashmap_put(*registry, call, q);
524 async_polkit_query_free(q);
528 q->registry = *registry;
530 r = sd_bus_call_async(call->bus, &q->slot, pk, async_polkit_callback, q, 0);
532 async_polkit_query_free(q);
542 void bus_verify_polkit_async_registry_free(Hashmap *registry) {
544 hashmap_free_with_destructor(registry, async_polkit_query_free);
548 #if 0 /// UNNEEDED by elogind
549 int bus_check_peercred(sd_bus *c) {
555 fd = sd_bus_get_fd(c);
559 r = getpeercred(fd, &ucred);
563 if (ucred.uid != 0 && ucred.uid != geteuid())
569 int bus_connect_system_systemd(sd_bus **_bus) {
570 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
576 return sd_bus_default_system(_bus);
578 /* If we are root then let's talk directly to the system
579 * instance, instead of going via the bus */
581 r = sd_bus_new(&bus);
585 r = sd_bus_set_address(bus, "unix:path=/run/systemd/private");
589 r = sd_bus_start(bus);
591 return sd_bus_default_system(_bus);
593 r = bus_check_peercred(bus);
597 *_bus = TAKE_PTR(bus);
602 int bus_connect_user_systemd(sd_bus **_bus) {
603 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
604 _cleanup_free_ char *ee = NULL;
610 e = secure_getenv("XDG_RUNTIME_DIR");
612 return sd_bus_default_user(_bus);
614 ee = bus_address_escape(e);
618 r = sd_bus_new(&bus);
622 bus->address = strjoin("unix:path=", ee, "/systemd/private");
626 r = sd_bus_start(bus);
628 return sd_bus_default_user(_bus);
630 r = bus_check_peercred(bus);
634 *_bus = TAKE_PTR(bus);
640 #define print_property(name, fmt, ...) \
643 printf(fmt "\n", __VA_ARGS__); \
645 printf("%s=" fmt "\n", name, __VA_ARGS__); \
648 int bus_print_property(const char *name, sd_bus_message *m, bool value, bool all) {
650 const char *contents;
656 r = sd_bus_message_peek_type(m, &type, &contents);
662 case SD_BUS_TYPE_STRING: {
665 r = sd_bus_message_read_basic(m, type, &s);
669 if (all || !isempty(s)) {
672 /* This property has a single value, so we need to take
673 * care not to print a new line, everything else is OK. */
674 good = !strchr(s, '\n');
675 print_property(name, "%s", good ? s : "[unprintable]");
681 case SD_BUS_TYPE_BOOLEAN: {
684 r = sd_bus_message_read_basic(m, type, &b);
688 print_property(name, "%s", yes_no(b));
693 case SD_BUS_TYPE_UINT64: {
696 r = sd_bus_message_read_basic(m, type, &u);
700 /* Yes, heuristics! But we can change this check
701 * should it turn out to not be sufficient */
703 if (endswith(name, "Timestamp") ||
704 STR_IN_SET(name, "NextElapseUSecRealtime", "LastTriggerUSec", "TimeUSec", "RTCTimeUSec")) {
705 char timestamp[FORMAT_TIMESTAMP_MAX];
708 t = format_timestamp(timestamp, sizeof(timestamp), u);
710 print_property(name, "%s", strempty(t));
712 } else if (strstr(name, "USec")) {
713 char timespan[FORMAT_TIMESPAN_MAX];
715 print_property(name, "%s", format_timespan(timespan, sizeof(timespan), u, 0));
716 } else if (streq(name, "RestrictNamespaces")) {
717 _cleanup_free_ char *s = NULL;
720 if ((u & NAMESPACE_FLAGS_ALL) == 0)
722 else if ((u & NAMESPACE_FLAGS_ALL) == NAMESPACE_FLAGS_ALL)
725 r = namespace_flags_to_string(u, &s);
732 print_property(name, "%s", result);
734 } else if (streq(name, "MountFlags")) {
737 result = mount_propagation_flags_to_string(u);
741 print_property(name, "%s", result);
743 } else if (STR_IN_SET(name, "CapabilityBoundingSet", "AmbientCapabilities")) {
744 _cleanup_free_ char *s = NULL;
746 r = capability_set_to_string_alloc(u, &s);
750 print_property(name, "%s", s);
752 } else if ((STR_IN_SET(name, "CPUWeight", "StartupCPUWeight", "IOWeight", "StartupIOWeight") && u == CGROUP_WEIGHT_INVALID) ||
753 (STR_IN_SET(name, "CPUShares", "StartupCPUShares") && u == CGROUP_CPU_SHARES_INVALID) ||
754 (STR_IN_SET(name, "BlockIOWeight", "StartupBlockIOWeight") && u == CGROUP_BLKIO_WEIGHT_INVALID) ||
755 (STR_IN_SET(name, "MemoryCurrent", "TasksCurrent") && u == (uint64_t) -1) ||
756 (endswith(name, "NSec") && u == (uint64_t) -1))
758 print_property(name, "%s", "[not set]");
760 else if ((STR_IN_SET(name, "MemoryLow", "MemoryHigh", "MemoryMax", "MemorySwapMax", "MemoryLimit") && u == CGROUP_LIMIT_MAX) ||
761 (STR_IN_SET(name, "TasksMax", "DefaultTasksMax") && u == (uint64_t) -1) ||
762 (startswith(name, "Limit") && u == (uint64_t) -1) ||
763 (startswith(name, "DefaultLimit") && u == (uint64_t) -1))
765 print_property(name, "%s", "infinity");
767 print_property(name, "%"PRIu64, u);
772 case SD_BUS_TYPE_INT64: {
775 r = sd_bus_message_read_basic(m, type, &i);
779 print_property(name, "%"PRIi64, i);
784 case SD_BUS_TYPE_UINT32: {
787 r = sd_bus_message_read_basic(m, type, &u);
791 if (strstr(name, "UMask") || strstr(name, "Mode"))
792 print_property(name, "%04o", u);
793 else if (streq(name, "UID")) {
794 if (u == UID_INVALID)
795 print_property(name, "%s", "[not set]");
797 print_property(name, "%"PRIu32, u);
798 } else if (streq(name, "GID")) {
799 if (u == GID_INVALID)
800 print_property(name, "%s", "[not set]");
802 print_property(name, "%"PRIu32, u);
804 print_property(name, "%"PRIu32, u);
809 case SD_BUS_TYPE_INT32: {
812 r = sd_bus_message_read_basic(m, type, &i);
816 print_property(name, "%"PRIi32, i);
820 case SD_BUS_TYPE_DOUBLE: {
823 r = sd_bus_message_read_basic(m, type, &d);
827 print_property(name, "%g", d);
831 case SD_BUS_TYPE_ARRAY:
832 if (streq(contents, "s")) {
836 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, contents);
840 while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &str)) > 0) {
846 /* This property has multiple space-separated values, so
847 * neither spaces nor newlines can be allowed in a value. */
848 good = str[strcspn(str, " \n")] == '\0';
850 printf("%s%s", first ? "" : " ", good ? str : "[unprintable]");
857 if (first && all && !value)
862 r = sd_bus_message_exit_container(m);
868 } else if (streq(contents, "y")) {
872 r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, (const void**) &u, &n);
882 for (i = 0; i < n; i++)
883 printf("%02x", u[i]);
890 } else if (streq(contents, "u")) {
894 r = sd_bus_message_read_array(m, SD_BUS_TYPE_UINT32, (const void**) &u, &n);
904 for (i = 0; i < n; i++)
905 printf("%08x", u[i]);
919 int bus_message_print_all_properties(
921 bus_message_print_t func,
925 Set **found_properties) {
931 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
935 while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
937 const char *contents;
939 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &name);
943 if (found_properties) {
944 r = set_ensure_allocated(found_properties, &string_hash_ops);
948 r = set_put(*found_properties, name);
949 if (r < 0 && r != EEXIST)
953 if (!filter || strv_find(filter, name)) {
954 r = sd_bus_message_peek_type(m, NULL, &contents);
958 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
963 r = func(name, m, value, all);
965 r = bus_print_property(name, m, value, all);
970 printf("%s=[unprintable]\n", name);
971 /* skip what we didn't read */
972 r = sd_bus_message_skip(m, contents);
977 r = sd_bus_message_exit_container(m);
981 r = sd_bus_message_skip(m, "v");
986 r = sd_bus_message_exit_container(m);
993 r = sd_bus_message_exit_container(m);
1000 int bus_print_all_properties(
1004 bus_message_print_t func,
1008 Set **found_properties) {
1010 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1011 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1017 r = sd_bus_call_method(bus,
1020 "org.freedesktop.DBus.Properties",
1028 return bus_message_print_all_properties(reply, func, filter, value, all, found_properties);
1031 int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1032 sd_id128_t *p = userdata;
1037 r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n);
1044 memcpy((*p).bytes, v, n);
1051 static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, unsigned flags, sd_bus_error *error, void *userdata) {
1055 r = sd_bus_message_peek_type(m, &type, NULL);
1061 case SD_BUS_TYPE_STRING: {
1062 const char **p = userdata;
1065 r = sd_bus_message_read_basic(m, type, &s);
1072 if (flags & BUS_MAP_STRDUP)
1073 return free_and_strdup((char **) userdata, s);
1079 case SD_BUS_TYPE_ARRAY: {
1080 _cleanup_strv_free_ char **l = NULL;
1081 char ***p = userdata;
1083 r = bus_message_read_strv_extend(m, &l);
1087 return strv_free_and_replace(*p, l);
1090 case SD_BUS_TYPE_BOOLEAN: {
1093 r = sd_bus_message_read_basic(m, type, &b);
1097 if (flags & BUS_MAP_BOOLEAN_AS_BOOL)
1098 *(bool*) userdata = b;
1100 *(int*) userdata = b;
1105 case SD_BUS_TYPE_INT32:
1106 case SD_BUS_TYPE_UINT32: {
1107 uint32_t u, *p = userdata;
1109 r = sd_bus_message_read_basic(m, type, &u);
1117 case SD_BUS_TYPE_INT64:
1118 case SD_BUS_TYPE_UINT64: {
1119 uint64_t t, *p = userdata;
1121 r = sd_bus_message_read_basic(m, type, &t);
1129 case SD_BUS_TYPE_DOUBLE: {
1130 double d, *p = userdata;
1132 r = sd_bus_message_read_basic(m, type, &d);
1143 int bus_message_map_all_properties(
1145 const struct bus_properties_map *map,
1147 sd_bus_error *error,
1155 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
1159 while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1160 const struct bus_properties_map *prop;
1162 const char *contents;
1166 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
1170 for (i = 0, prop = NULL; map[i].member; i++)
1171 if (streq(map[i].member, member)) {
1177 r = sd_bus_message_peek_type(m, NULL, &contents);
1181 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
1185 v = (uint8_t *)userdata + prop->offset;
1187 r = prop->set(sd_bus_message_get_bus(m), member, m, error, v);
1189 r = map_basic(sd_bus_message_get_bus(m), member, m, flags, error, v);
1193 r = sd_bus_message_exit_container(m);
1197 r = sd_bus_message_skip(m, "v");
1202 r = sd_bus_message_exit_container(m);
1209 return sd_bus_message_exit_container(m);
1212 #if 0 /// UNNEEDED by elogind
1213 int bus_message_map_properties_changed(
1215 const struct bus_properties_map *map,
1217 sd_bus_error *error,
1221 int r, invalidated, i;
1226 r = bus_message_map_all_properties(m, map, flags, error, userdata);
1230 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s");
1235 while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0)
1236 for (i = 0; map[i].member; i++)
1237 if (streq(map[i].member, member)) {
1244 r = sd_bus_message_exit_container(m);
1252 int bus_map_all_properties(
1254 const char *destination,
1256 const struct bus_properties_map *map,
1258 sd_bus_error *error,
1259 sd_bus_message **reply,
1262 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1266 assert(destination);
1269 assert(reply || (flags & BUS_MAP_STRDUP));
1271 r = sd_bus_call_method(
1275 "org.freedesktop.DBus.Properties",
1283 r = bus_message_map_all_properties(m, map, flags, error, userdata);
1288 *reply = sd_bus_message_ref(m);
1293 int bus_connect_transport(BusTransport transport, const char *host, bool user, sd_bus **ret) {
1294 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1297 assert(transport >= 0);
1298 assert(transport < _BUS_TRANSPORT_MAX);
1301 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1302 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1304 switch (transport) {
1306 case BUS_TRANSPORT_LOCAL:
1307 #if 0 /// elogind does not support a user bus
1309 r = sd_bus_default_user(&bus);
1312 if (sd_booted() <= 0) {
1313 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1314 log_error("System has not been booted with elogind as init system (PID 1). Can't operate.");
1318 r = sd_bus_default_system(&bus);
1322 case BUS_TRANSPORT_REMOTE:
1323 r = sd_bus_open_system_remote(&bus, host);
1326 case BUS_TRANSPORT_MACHINE:
1327 r = sd_bus_open_system_machine(&bus, host);
1331 assert_not_reached("Hmm, unknown transport type.");
1336 r = sd_bus_set_exit_on_disconnect(bus, true);
1340 *ret = TAKE_PTR(bus);
1345 #if 0 /// UNNEEDED by elogind
1346 int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1349 assert(transport >= 0);
1350 assert(transport < _BUS_TRANSPORT_MAX);
1353 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1354 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1356 switch (transport) {
1358 case BUS_TRANSPORT_LOCAL:
1360 r = bus_connect_user_systemd(bus);
1362 if (sd_booted() <= 0) {
1363 /* Print a friendly message when the local system is actually not running systemd as PID 1. */
1364 log_error("System has not been booted with systemd as init system (PID 1). Can't operate.");
1368 r = bus_connect_system_systemd(bus);
1372 case BUS_TRANSPORT_REMOTE:
1373 r = sd_bus_open_system_remote(bus, host);
1376 case BUS_TRANSPORT_MACHINE:
1377 r = sd_bus_open_system_machine(bus, host);
1381 assert_not_reached("Hmm, unknown transport type.");
1388 int bus_property_get_bool(
1391 const char *interface,
1392 const char *property,
1393 sd_bus_message *reply,
1395 sd_bus_error *error) {
1397 int b = *(bool*) userdata;
1399 return sd_bus_message_append_basic(reply, 'b', &b);
1402 int bus_property_set_bool(
1405 const char *interface,
1406 const char *property,
1407 sd_bus_message *value,
1409 sd_bus_error *error) {
1413 r = sd_bus_message_read(value, "b", &b);
1417 *(bool*) userdata = b;
1421 #if 0 /// UNNEEDED by elogind
1422 int bus_property_get_id128(
1425 const char *interface,
1426 const char *property,
1427 sd_bus_message *reply,
1429 sd_bus_error *error) {
1431 sd_id128_t *id = userdata;
1433 if (sd_id128_is_null(*id)) /* Add an empty array if the ID is zero */
1434 return sd_bus_message_append(reply, "ay", 0);
1436 return sd_bus_message_append_array(reply, 'y', id->bytes, 16);
1440 #if __SIZEOF_SIZE_T__ != 8
1441 int bus_property_get_size(
1444 const char *interface,
1445 const char *property,
1446 sd_bus_message *reply,
1448 sd_bus_error *error) {
1450 uint64_t sz = *(size_t*) userdata;
1452 return sd_bus_message_append_basic(reply, 't', &sz);
1456 #if __SIZEOF_LONG__ != 8
1457 int bus_property_get_long(
1460 const char *interface,
1461 const char *property,
1462 sd_bus_message *reply,
1464 sd_bus_error *error) {
1466 int64_t l = *(long*) userdata;
1468 return sd_bus_message_append_basic(reply, 'x', &l);
1471 int bus_property_get_ulong(
1474 const char *interface,
1475 const char *property,
1476 sd_bus_message *reply,
1478 sd_bus_error *error) {
1480 uint64_t ul = *(unsigned long*) userdata;
1482 return sd_bus_message_append_basic(reply, 't', &ul);
1486 int bus_log_parse_error(int r) {
1487 return log_error_errno(r, "Failed to parse bus message: %m");
1490 #if 0 /// UNNEEDED by elogind
1491 int bus_log_create_error(int r) {
1492 return log_error_errno(r, "Failed to create bus message: %m");
1496 #if 0 /// UNNEEDED by elogind
1498 * bus_path_encode_unique() - encode unique object path
1499 * @b: bus connection or NULL
1500 * @prefix: object path prefix
1501 * @sender_id: unique-name of client, or NULL
1502 * @external_id: external ID to be chosen by client, or NULL
1503 * @ret_path: storage for encoded object path pointer
1505 * Whenever we provide a bus API that allows clients to create and manage
1506 * server-side objects, we need to provide a unique name for these objects. If
1507 * we let the server choose the name, we suffer from a race condition: If a
1508 * client creates an object asynchronously, it cannot destroy that object until
1509 * it received the method reply. It cannot know the name of the new object,
1510 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
1512 * Therefore, many APIs allow the client to choose the unique name for newly
1513 * created objects. There're two problems to solve, though:
1514 * 1) Object names are usually defined via dbus object paths, which are
1515 * usually globally namespaced. Therefore, multiple clients must be able
1516 * to choose unique object names without interference.
1517 * 2) If multiple libraries share the same bus connection, they must be
1518 * able to choose unique object names without interference.
1519 * The first problem is solved easily by prefixing a name with the
1520 * unique-bus-name of a connection. The server side must enforce this and
1521 * reject any other name. The second problem is solved by providing unique
1522 * suffixes from within sd-bus.
1524 * This helper allows clients to create unique object-paths. It uses the
1525 * template '/prefix/sender_id/external_id' and returns the new path in
1526 * @ret_path (must be freed by the caller).
1527 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
1528 * NULL, this function allocates a unique suffix via @b (by requesting a new
1529 * cookie). If both @sender_id and @external_id are given, @b can be passed as
1532 * Returns: 0 on success, negative error code on failure.
1534 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
1535 _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
1536 char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
1539 assert_return(b || (sender_id && external_id), -EINVAL);
1540 assert_return(object_path_is_valid(prefix), -EINVAL);
1541 assert_return(ret_path, -EINVAL);
1544 r = sd_bus_get_unique_name(b, &sender_id);
1550 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
1551 external_id = external_buf;
1554 sender_label = bus_label_escape(sender_id);
1558 external_label = bus_label_escape(external_id);
1559 if (!external_label)
1562 p = strjoin(prefix, "/", sender_label, "/", external_label);
1571 * bus_path_decode_unique() - decode unique object path
1572 * @path: object path to decode
1573 * @prefix: object path prefix
1574 * @ret_sender: output parameter for sender-id label
1575 * @ret_external: output parameter for external-id label
1577 * This does the reverse of bus_path_encode_unique() (see its description for
1578 * details). Both trailing labels, sender-id and external-id, are unescaped and
1579 * returned in the given output parameters (the caller must free them).
1581 * Note that this function returns 0 if the path does not match the template
1582 * (see bus_path_encode_unique()), 1 if it matched.
1584 * Returns: Negative error code on failure, 0 if the given object path does not
1585 * match the template (return parameters are set to NULL), 1 if it was
1586 * parsed successfully (return parameters contain allocated labels).
1588 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
1590 char *sender, *external;
1592 assert(object_path_is_valid(path));
1593 assert(object_path_is_valid(prefix));
1595 assert(ret_external);
1597 p = object_path_startswith(path, prefix);
1600 *ret_external = NULL;
1607 *ret_external = NULL;
1611 sender = bus_label_unescape_n(p, q - p);
1612 external = bus_label_unescape(q + 1);
1613 if (!sender || !external) {
1619 *ret_sender = sender;
1620 *ret_external = external;
1625 #if 0 /// UNNEEDED by elogind
1626 int bus_property_get_rlimit(
1629 const char *interface,
1630 const char *property,
1631 sd_bus_message *reply,
1633 sd_bus_error *error) {
1635 const char *is_soft;
1644 is_soft = endswith(property, "Soft");
1646 rl = *(struct rlimit**) userdata;
1648 x = is_soft ? rl->rlim_cur : rl->rlim_max;
1650 struct rlimit buf = {};
1654 /* Chop off "Soft" suffix */
1655 s = is_soft ? strndupa(property, is_soft - property) : property;
1657 /* Skip over any prefix, such as "Default" */
1658 assert_se(p = strstr(s, "Limit"));
1660 z = rlimit_from_string(p + 5);
1663 (void) getrlimit(z, &buf);
1664 x = is_soft ? buf.rlim_cur : buf.rlim_max;
1667 /* rlim_t might have different sizes, let's map RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on all
1669 u = x == RLIM_INFINITY ? (uint64_t) -1 : (uint64_t) x;
1671 return sd_bus_message_append(reply, "t", u);
1674 int bus_track_add_name_many(sd_bus_track *t, char **l) {
1680 /* Continues adding after failure, and returns the first failure. */
1682 STRV_FOREACH(i, l) {
1685 k = sd_bus_track_add_name(t, *i);
1686 if (k < 0 && r >= 0)
1694 int bus_open_system_watch_bind_with_description(sd_bus **ret, const char *description) {
1695 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1701 /* Match like sd_bus_open_system(), but with the "watch_bind" feature and the Connected() signal turned on. */
1703 r = sd_bus_new(&bus);
1708 r = sd_bus_set_description(bus, description);
1713 e = secure_getenv("DBUS_SYSTEM_BUS_ADDRESS");
1715 e = DEFAULT_SYSTEM_BUS_ADDRESS;
1717 r = sd_bus_set_address(bus, e);
1721 r = sd_bus_set_bus_client(bus, true);
1725 r = sd_bus_set_trusted(bus, true);
1729 r = sd_bus_negotiate_creds(bus, true, SD_BUS_CREDS_UID|SD_BUS_CREDS_EUID|SD_BUS_CREDS_EFFECTIVE_CAPS);
1733 r = sd_bus_set_watch_bind(bus, true);
1737 r = sd_bus_set_connected_signal(bus, true);
1741 r = sd_bus_start(bus);
1745 *ret = TAKE_PTR(bus);
1750 struct request_name_data {
1758 static void request_name_destroy_callback(void *userdata) {
1759 struct request_name_data *data = userdata;
1762 assert(data->n_ref > 0);
1764 log_info("%s n_ref=%u", __func__, data->n_ref);
1767 if (data->n_ref == 0)
1771 static int reload_dbus_handler(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1772 struct request_name_data *data = userdata;
1773 const sd_bus_error *e;
1778 assert(data->n_ref > 0);
1780 e = sd_bus_message_get_error(m);
1782 log_error_errno(sd_bus_error_get_errno(e), "Failed to reload DBus configuration: %s", e->message);
1786 /* Here, use the default request name handler to avoid an infinite loop of reloading and requesting. */
1787 r = sd_bus_request_name_async(sd_bus_message_get_bus(m), NULL, data->name, data->flags, NULL, data->userdata);
1789 log_error_errno(r, "Failed to request name: %m");
1794 static int request_name_handler_may_reload_dbus(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
1795 struct request_name_data *data = userdata;
1802 if (sd_bus_message_is_method_error(m, NULL)) {
1803 const sd_bus_error *e = sd_bus_message_get_error(m);
1804 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1806 if (!sd_bus_error_has_name(e, SD_BUS_ERROR_ACCESS_DENIED)) {
1807 log_debug_errno(sd_bus_error_get_errno(e),
1808 "Unable to request name, failing connection: %s",
1811 bus_enter_closing(sd_bus_message_get_bus(m));
1815 log_debug_errno(sd_bus_error_get_errno(e),
1816 "Unable to request name, will retry after reloading DBus configuration: %s",
1819 /* If systemd-timesyncd.service enables DynamicUser= and dbus.service
1820 * started before the dynamic user is realized, then the DBus policy
1821 * about timesyncd has not been enabled yet. So, let's try to reload
1822 * DBus configuration, and after that request the name again. Note that it
1823 * seems that no privileges are necessary to call the following method. */
1825 r = sd_bus_call_method_async(
1826 sd_bus_message_get_bus(m),
1828 "org.freedesktop.DBus",
1829 "/org/freedesktop/DBus",
1830 "org.freedesktop.DBus",
1832 reload_dbus_handler,
1835 log_error_errno(r, "Failed to reload DBus configuration: %m");
1836 bus_enter_closing(sd_bus_message_get_bus(m));
1841 assert_se(sd_bus_slot_set_destroy_callback(slot, request_name_destroy_callback) >= 0);
1843 r = sd_bus_slot_set_floating(slot, true);
1850 r = sd_bus_message_read(m, "u", &ret);
1856 case BUS_NAME_ALREADY_OWNER:
1857 log_debug("Already owner of requested service name, ignoring.");
1860 case BUS_NAME_IN_QUEUE:
1861 log_debug("In queue for requested service name.");
1864 case BUS_NAME_PRIMARY_OWNER:
1865 log_debug("Successfully acquired requested service name.");
1868 case BUS_NAME_EXISTS:
1869 log_debug("Requested service name already owned, failing connection.");
1870 bus_enter_closing(sd_bus_message_get_bus(m));
1874 log_debug("Unexpected response from RequestName(), failing connection.");
1875 bus_enter_closing(sd_bus_message_get_bus(m));
1879 int bus_request_name_async_may_reload_dbus(sd_bus *bus, sd_bus_slot **ret_slot, const char *name, uint64_t flags, void *userdata) {
1880 _cleanup_free_ struct request_name_data *data = NULL;
1881 _cleanup_(sd_bus_slot_unrefp) sd_bus_slot *slot = NULL;
1884 data = new(struct request_name_data, 1);
1888 *data = (struct request_name_data) {
1892 .userdata = userdata,
1895 r = sd_bus_request_name_async(bus, &slot, name, flags, request_name_handler_may_reload_dbus, data);
1899 assert_se(sd_bus_slot_set_destroy_callback(slot, request_name_destroy_callback) >= 0);
1903 *ret_slot = TAKE_PTR(slot);
1905 r = sd_bus_slot_set_floating(slot, true);
1913 int bus_reply_pair_array(sd_bus_message *m, char **l) {
1914 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1920 /* Reply to the specified message with a message containing a dictionary put together from the specified
1923 r = sd_bus_message_new_method_return(m, &reply);
1927 r = sd_bus_message_open_container(reply, 'a', "{ss}");
1931 STRV_FOREACH_PAIR(k, v, l) {
1932 r = sd_bus_message_append(reply, "{ss}", *k, *v);
1937 r = sd_bus_message_close_container(reply);
1941 return sd_bus_send(NULL, reply, NULL);