1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2013 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/socket.h>
24 #include "sd-daemon.h"
30 #include "path-util.h"
33 #include "signal-util.h"
34 #include "unit-name.h"
37 #include "bus-error.h"
38 #include "bus-label.h"
39 #include "bus-message.h"
41 #include "bus-internal.h"
43 static int name_owner_change_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
44 sd_event *e = userdata;
49 sd_bus_close(sd_bus_message_get_bus(m));
55 int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name) {
56 _cleanup_free_ char *match = NULL;
64 /* We unregister the name here and then wait for the
65 * NameOwnerChanged signal for this event to arrive before we
66 * quit. We do this in order to make sure that any queued
67 * requests are still processed before we really exit. */
69 r = sd_bus_get_unique_name(bus, &unique);
74 "sender='org.freedesktop.DBus',"
76 "interface='org.freedesktop.DBus',"
77 "member='NameOwnerChanged',"
78 "path='/org/freedesktop/DBus',"
81 "arg2=''", name, unique);
85 r = sd_bus_add_match(bus, NULL, match, name_owner_change_callback, e);
89 r = sd_bus_release_name(bus, name);
96 int bus_event_loop_with_idle(
101 check_idle_t check_idle,
103 bool exiting = false;
113 r = sd_event_get_state(e);
116 if (r == SD_EVENT_FINISHED)
120 idle = check_idle(userdata);
124 r = sd_event_run(e, exiting || !idle ? (uint64_t) -1 : timeout);
128 if (r == 0 && !exiting && idle) {
130 r = sd_bus_try_close(bus);
134 /* Fallback for dbus1 connections: we
135 * unregister the name and wait for the
136 * response to come through for it */
137 if (r == -EOPNOTSUPP) {
139 /* Inform the service manager that we
140 * are going down, so that it will
141 * queue all further start requests,
142 * instead of assuming we are already
144 sd_notify(false, "STOPPING=1");
146 r = bus_async_unregister_and_exit(e, bus, name);
162 r = sd_event_get_exit_code(e, &code);
169 int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error) {
170 _cleanup_bus_message_unref_ sd_bus_message *rep = NULL;
171 int r, has_owner = 0;
176 r = sd_bus_call_method(c,
177 "org.freedesktop.DBus",
178 "/org/freedesktop/dbus",
179 "org.freedesktop.DBus",
188 r = sd_bus_message_read_basic(rep, 'b', &has_owner);
190 return sd_bus_error_set_errno(error, r);
195 static int check_good_user(sd_bus_message *m, uid_t good_user) {
196 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
202 if (good_user == UID_INVALID)
205 r = sd_bus_query_sender_creds(m, SD_BUS_CREDS_EUID, &creds);
209 /* Don't trust augmented credentials for authorization */
210 assert_return((sd_bus_creds_get_augmented_mask(creds) & SD_BUS_CREDS_EUID) == 0, -EPERM);
212 r = sd_bus_creds_get_euid(creds, &sender_uid);
216 return sender_uid == good_user;
220 sd_bus_message *call,
232 /* Tests non-interactively! */
234 r = check_good_user(call, good_user);
238 r = sd_bus_query_sender_privilege(call, capability);
245 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
246 int authorized = false, challenge = false;
249 sender = sd_bus_message_get_sender(call);
253 r = sd_bus_call_method(
255 "org.freedesktop.PolicyKit1",
256 "/org/freedesktop/PolicyKit1/Authority",
257 "org.freedesktop.PolicyKit1.Authority",
258 "CheckAuthorization",
262 "system-bus-name", 1, "name", "s", sender,
269 /* Treat no PK available as access denied */
270 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN)) {
271 sd_bus_error_free(e);
278 r = sd_bus_message_enter_container(reply, 'r', "bba{ss}");
282 r = sd_bus_message_read(reply, "bb", &authorized, &challenge);
290 *_challenge = challenge;
301 typedef struct AsyncPolkitQuery {
302 sd_bus_message *request, *reply;
303 sd_bus_message_handler_t callback;
309 static void async_polkit_query_free(AsyncPolkitQuery *q) {
314 sd_bus_slot_unref(q->slot);
316 if (q->registry && q->request)
317 hashmap_remove(q->registry, q->request);
319 sd_bus_message_unref(q->request);
320 sd_bus_message_unref(q->reply);
325 static int async_polkit_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
326 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
327 AsyncPolkitQuery *q = userdata;
333 q->slot = sd_bus_slot_unref(q->slot);
334 q->reply = sd_bus_message_ref(reply);
336 r = sd_bus_message_rewind(q->request, true);
338 r = sd_bus_reply_method_errno(q->request, r, NULL);
342 r = q->callback(q->request, q->userdata, &error_buffer);
343 r = bus_maybe_reply_error(q->request, r, &error_buffer);
346 async_polkit_query_free(q);
353 int bus_verify_polkit_async(
354 sd_bus_message *call,
360 sd_bus_error *error) {
363 _cleanup_bus_message_unref_ sd_bus_message *pk = NULL;
366 sd_bus_message_handler_t callback;
376 r = check_good_user(call, good_user);
381 q = hashmap_get(*registry, call);
383 int authorized, challenge;
385 /* This is the second invocation of this function, and
386 * there's already a response from polkit, let's
390 if (sd_bus_message_is_method_error(q->reply, NULL)) {
391 const sd_bus_error *e;
393 /* Copy error from polkit reply */
394 e = sd_bus_message_get_error(q->reply);
395 sd_bus_error_copy(error, e);
397 /* Treat no PK available as access denied */
398 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN))
401 return -sd_bus_error_get_errno(e);
404 r = sd_bus_message_enter_container(q->reply, 'r', "bba{ss}");
406 r = sd_bus_message_read(q->reply, "bb", &authorized, &challenge);
415 return sd_bus_error_set(error, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED, "Interactive authentication required.");
421 r = sd_bus_query_sender_privilege(call, capability);
428 if (sd_bus_get_current_message(call->bus) != call)
431 callback = sd_bus_get_current_handler(call->bus);
435 userdata = sd_bus_get_current_userdata(call->bus);
437 sender = sd_bus_message_get_sender(call);
441 c = sd_bus_message_get_allow_interactive_authorization(call);
447 r = hashmap_ensure_allocated(registry, NULL);
451 r = sd_bus_message_new_method_call(
454 "org.freedesktop.PolicyKit1",
455 "/org/freedesktop/PolicyKit1/Authority",
456 "org.freedesktop.PolicyKit1.Authority",
457 "CheckAuthorization");
461 r = sd_bus_message_append(
464 "system-bus-name", 1, "name", "s", sender,
472 q = new0(AsyncPolkitQuery, 1);
476 q->request = sd_bus_message_ref(call);
477 q->callback = callback;
478 q->userdata = userdata;
480 r = hashmap_put(*registry, call, q);
482 async_polkit_query_free(q);
486 q->registry = *registry;
488 r = sd_bus_call_async(call->bus, &q->slot, pk, async_polkit_callback, q, 0);
490 async_polkit_query_free(q);
500 void bus_verify_polkit_async_registry_free(Hashmap *registry) {
504 while ((q = hashmap_steal_first(registry)))
505 async_polkit_query_free(q);
507 hashmap_free(registry);
511 int bus_check_peercred(sd_bus *c) {
518 fd = sd_bus_get_fd(c);
522 l = sizeof(struct ucred);
523 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
526 if (l != sizeof(struct ucred))
529 if (ucred.uid != 0 && ucred.uid != geteuid())
535 int bus_open_system_systemd(sd_bus **_bus) {
536 _cleanup_bus_unref_ sd_bus *bus = NULL;
542 return sd_bus_open_system(_bus);
544 /* If we are root and kdbus is not available, then let's talk
545 * directly to the system instance, instead of going via the
548 r = sd_bus_new(&bus);
552 r = sd_bus_set_address(bus, KERNEL_SYSTEM_BUS_ADDRESS);
556 bus->bus_client = true;
558 r = sd_bus_start(bus);
565 bus = sd_bus_unref(bus);
567 r = sd_bus_new(&bus);
571 r = sd_bus_set_address(bus, "unix:path=/run/systemd/private");
575 r = sd_bus_start(bus);
577 return sd_bus_open_system(_bus);
579 r = bus_check_peercred(bus);
589 int bus_open_user_systemd(sd_bus **_bus) {
590 _cleanup_bus_unref_ sd_bus *bus = NULL;
591 _cleanup_free_ char *ee = NULL;
595 /* Try via kdbus first, and then directly */
599 r = sd_bus_new(&bus);
603 if (asprintf(&bus->address, KERNEL_USER_BUS_ADDRESS_FMT, getuid()) < 0)
606 bus->bus_client = true;
608 r = sd_bus_start(bus);
615 bus = sd_bus_unref(bus);
617 e = secure_getenv("XDG_RUNTIME_DIR");
619 return sd_bus_open_user(_bus);
621 ee = bus_address_escape(e);
625 r = sd_bus_new(&bus);
629 bus->address = strjoin("unix:path=", ee, "/systemd/private", NULL);
633 r = sd_bus_start(bus);
635 return sd_bus_open_user(_bus);
637 r = bus_check_peercred(bus);
647 int bus_print_property(const char *name, sd_bus_message *property, bool all) {
649 const char *contents;
655 r = sd_bus_message_peek_type(property, &type, &contents);
661 case SD_BUS_TYPE_STRING: {
664 r = sd_bus_message_read_basic(property, type, &s);
668 if (all || !isempty(s)) {
669 _cleanup_free_ char *escaped = NULL;
671 escaped = xescape(s, "\n");
675 printf("%s=%s\n", name, escaped);
681 case SD_BUS_TYPE_BOOLEAN: {
684 r = sd_bus_message_read_basic(property, type, &b);
688 printf("%s=%s\n", name, yes_no(b));
693 case SD_BUS_TYPE_UINT64: {
696 r = sd_bus_message_read_basic(property, 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 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
706 t = format_timestamp(timestamp, sizeof(timestamp), u);
708 printf("%s=%s\n", name, strempty(t));
710 } else if (strstr(name, "USec")) {
711 char timespan[FORMAT_TIMESPAN_MAX];
713 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u, 0));
715 printf("%s=%llu\n", name, (unsigned long long) u);
720 case SD_BUS_TYPE_INT64: {
723 r = sd_bus_message_read_basic(property, type, &i);
727 printf("%s=%lld\n", name, (long long) i);
732 case SD_BUS_TYPE_UINT32: {
735 r = sd_bus_message_read_basic(property, type, &u);
739 if (strstr(name, "UMask") || strstr(name, "Mode"))
740 printf("%s=%04o\n", name, u);
742 printf("%s=%u\n", name, (unsigned) u);
747 case SD_BUS_TYPE_INT32: {
750 r = sd_bus_message_read_basic(property, type, &i);
754 printf("%s=%i\n", name, (int) i);
758 case SD_BUS_TYPE_DOUBLE: {
761 r = sd_bus_message_read_basic(property, type, &d);
765 printf("%s=%g\n", name, d);
769 case SD_BUS_TYPE_ARRAY:
770 if (streq(contents, "s")) {
774 r = sd_bus_message_enter_container(property, SD_BUS_TYPE_ARRAY, contents);
778 while((r = sd_bus_message_read_basic(property, SD_BUS_TYPE_STRING, &str)) > 0) {
779 _cleanup_free_ char *escaped = NULL;
784 escaped = xescape(str, "\n ");
788 printf("%s%s", first ? "" : " ", escaped);
800 r = sd_bus_message_exit_container(property);
806 } else if (streq(contents, "y")) {
810 r = sd_bus_message_read_array(property, SD_BUS_TYPE_BYTE, (const void**) &u, &n);
819 for (i = 0; i < n; i++)
820 printf("%02x", u[i]);
827 } else if (streq(contents, "u")) {
831 r = sd_bus_message_read_array(property, SD_BUS_TYPE_UINT32, (const void**) &u, &n);
840 for (i = 0; i < n; i++)
841 printf("%08x", u[i]);
855 int bus_print_all_properties(sd_bus *bus, const char *dest, const char *path, char **filter, bool all) {
856 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
857 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
863 r = sd_bus_call_method(bus,
866 "org.freedesktop.DBus.Properties",
874 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "{sv}");
878 while ((r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
880 const char *contents;
882 r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &name);
886 if (!filter || strv_find(filter, name)) {
887 r = sd_bus_message_peek_type(reply, NULL, &contents);
891 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_VARIANT, contents);
895 r = bus_print_property(name, reply, all);
900 printf("%s=[unprintable]\n", name);
901 /* skip what we didn't read */
902 r = sd_bus_message_skip(reply, contents);
907 r = sd_bus_message_exit_container(reply);
911 r = sd_bus_message_skip(reply, "v");
916 r = sd_bus_message_exit_container(reply);
923 r = sd_bus_message_exit_container(reply);
930 int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
931 sd_id128_t *p = userdata;
936 r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n);
943 memcpy((*p).bytes, v, n);
950 static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
954 r = sd_bus_message_peek_type(m, &type, NULL);
959 case SD_BUS_TYPE_STRING: {
963 r = sd_bus_message_read_basic(m, type, &s);
970 r = free_and_strdup(p, s);
974 case SD_BUS_TYPE_ARRAY: {
975 _cleanup_strv_free_ char **l = NULL;
976 char ***p = userdata;
978 r = bus_message_read_strv_extend(m, &l);
989 case SD_BUS_TYPE_BOOLEAN: {
993 r = sd_bus_message_read_basic(m, type, &b);
1002 case SD_BUS_TYPE_UINT32: {
1004 uint32_t *p = userdata;
1006 r = sd_bus_message_read_basic(m, type, &u);
1015 case SD_BUS_TYPE_UINT64: {
1017 uint64_t *p = userdata;
1019 r = sd_bus_message_read_basic(m, type, &t);
1035 int bus_message_map_all_properties(
1037 const struct bus_properties_map *map,
1040 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1046 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
1050 while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1051 const struct bus_properties_map *prop;
1053 const char *contents;
1057 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
1061 for (i = 0, prop = NULL; map[i].member; i++)
1062 if (streq(map[i].member, member)) {
1068 r = sd_bus_message_peek_type(m, NULL, &contents);
1072 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
1076 v = (uint8_t *)userdata + prop->offset;
1078 r = prop->set(sd_bus_message_get_bus(m), member, m, &error, v);
1080 r = map_basic(sd_bus_message_get_bus(m), member, m, &error, v);
1084 r = sd_bus_message_exit_container(m);
1088 r = sd_bus_message_skip(m, "v");
1093 r = sd_bus_message_exit_container(m);
1100 return sd_bus_message_exit_container(m);
1103 int bus_message_map_properties_changed(
1105 const struct bus_properties_map *map,
1109 int r, invalidated, i;
1114 r = bus_message_map_all_properties(m, map, userdata);
1118 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s");
1123 while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0)
1124 for (i = 0; map[i].member; i++)
1125 if (streq(map[i].member, member)) {
1132 r = sd_bus_message_exit_container(m);
1139 int bus_map_all_properties(
1141 const char *destination,
1143 const struct bus_properties_map *map,
1146 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
1147 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1151 assert(destination);
1155 r = sd_bus_call_method(
1159 "org.freedesktop.DBus.Properties",
1167 return bus_message_map_all_properties(m, map, userdata);
1170 int bus_open_transport(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1173 assert(transport >= 0);
1174 assert(transport < _BUS_TRANSPORT_MAX);
1177 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1178 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1180 switch (transport) {
1182 case BUS_TRANSPORT_LOCAL:
1184 r = sd_bus_default_user(bus);
1186 r = sd_bus_default_system(bus);
1190 case BUS_TRANSPORT_REMOTE:
1191 r = sd_bus_open_system_remote(bus, host);
1194 case BUS_TRANSPORT_MACHINE:
1195 r = sd_bus_open_system_machine(bus, host);
1199 assert_not_reached("Hmm, unknown transport type.");
1205 int bus_open_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1208 assert(transport >= 0);
1209 assert(transport < _BUS_TRANSPORT_MAX);
1212 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1213 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1215 switch (transport) {
1217 case BUS_TRANSPORT_LOCAL:
1219 r = bus_open_user_systemd(bus);
1221 r = bus_open_system_systemd(bus);
1225 case BUS_TRANSPORT_REMOTE:
1226 r = sd_bus_open_system_remote(bus, host);
1229 case BUS_TRANSPORT_MACHINE:
1230 r = sd_bus_open_system_machine(bus, host);
1234 assert_not_reached("Hmm, unknown transport type.");
1240 int bus_property_get_bool(
1243 const char *interface,
1244 const char *property,
1245 sd_bus_message *reply,
1247 sd_bus_error *error) {
1249 int b = *(bool*) userdata;
1251 return sd_bus_message_append_basic(reply, 'b', &b);
1254 #if __SIZEOF_SIZE_T__ != 8
1255 int bus_property_get_size(
1258 const char *interface,
1259 const char *property,
1260 sd_bus_message *reply,
1262 sd_bus_error *error) {
1264 uint64_t sz = *(size_t*) userdata;
1266 return sd_bus_message_append_basic(reply, 't', &sz);
1270 #if __SIZEOF_LONG__ != 8
1271 int bus_property_get_long(
1274 const char *interface,
1275 const char *property,
1276 sd_bus_message *reply,
1278 sd_bus_error *error) {
1280 int64_t l = *(long*) userdata;
1282 return sd_bus_message_append_basic(reply, 'x', &l);
1285 int bus_property_get_ulong(
1288 const char *interface,
1289 const char *property,
1290 sd_bus_message *reply,
1292 sd_bus_error *error) {
1294 uint64_t ul = *(unsigned long*) userdata;
1296 return sd_bus_message_append_basic(reply, 't', &ul);
1300 int bus_log_parse_error(int r) {
1301 return log_error_errno(r, "Failed to parse bus message: %m");
1304 int bus_log_create_error(int r) {
1305 return log_error_errno(r, "Failed to create bus message: %m");
1308 int bus_parse_unit_info(sd_bus_message *message, UnitInfo *u) {
1314 return sd_bus_message_read(
1329 int bus_maybe_reply_error(sd_bus_message *m, int r, sd_bus_error *error) {
1333 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL)
1334 sd_bus_reply_method_errno(m, r, error);
1336 } else if (sd_bus_error_is_set(error)) {
1337 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL)
1338 sd_bus_reply_method_error(m, error);
1342 log_debug("Failed to process message [type=%s sender=%s path=%s interface=%s member=%s signature=%s]: %s",
1343 bus_message_type_to_string(m->header->type),
1346 strna(m->interface),
1348 strna(m->root_container.signature),
1349 bus_error_message(error, r));
1354 int bus_append_unit_property_assignment(sd_bus_message *m, const char *assignment) {
1355 const char *eq, *field;
1361 eq = strchr(assignment, '=');
1363 log_error("Not an assignment: %s", assignment);
1367 field = strndupa(assignment, eq - assignment);
1370 if (streq(field, "CPUQuota")) {
1374 r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, "CPUQuotaPerSecUSec");
1376 return bus_log_create_error(r);
1378 r = sd_bus_message_append(m, "v", "t", USEC_INFINITY);
1380 } else if (endswith(eq, "%")) {
1383 if (sscanf(eq, "%lf%%", &percent) != 1 || percent <= 0) {
1384 log_error("CPU quota '%s' invalid.", eq);
1388 r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, "CPUQuotaPerSecUSec");
1390 return bus_log_create_error(r);
1392 r = sd_bus_message_append(m, "v", "t", (usec_t) percent * USEC_PER_SEC / 100);
1394 log_error("CPU quota needs to be in percent.");
1399 return bus_log_create_error(r);
1404 r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, field);
1406 return bus_log_create_error(r);
1408 if (STR_IN_SET(field,
1409 "CPUAccounting", "MemoryAccounting", "BlockIOAccounting",
1410 "SendSIGHUP", "SendSIGKILL", "WakeSystem", "DefaultDependencies")) {
1412 r = parse_boolean(eq);
1414 log_error("Failed to parse boolean assignment %s.", assignment);
1418 r = sd_bus_message_append(m, "v", "b", r);
1420 } else if (streq(field, "MemoryLimit")) {
1423 r = parse_size(eq, 1024, &bytes);
1425 log_error("Failed to parse bytes specification %s", assignment);
1429 r = sd_bus_message_append(m, "v", "t", (uint64_t) bytes);
1431 } else if (STR_IN_SET(field, "CPUShares", "BlockIOWeight")) {
1434 r = safe_atou64(eq, &u);
1436 log_error("Failed to parse %s value %s.", field, eq);
1440 r = sd_bus_message_append(m, "v", "t", u);
1442 } else if (STR_IN_SET(field, "User", "Group", "DevicePolicy", "KillMode"))
1443 r = sd_bus_message_append(m, "v", "s", eq);
1445 else if (streq(field, "DeviceAllow")) {
1448 r = sd_bus_message_append(m, "v", "a(ss)", 0);
1450 const char *path, *rwm, *e;
1452 e = strchr(eq, ' ');
1454 path = strndupa(eq, e - eq);
1461 if (!path_startswith(path, "/dev")) {
1462 log_error("%s is not a device file in /dev.", path);
1466 r = sd_bus_message_append(m, "v", "a(ss)", 1, path, rwm);
1469 } else if (STR_IN_SET(field, "BlockIOReadBandwidth", "BlockIOWriteBandwidth")) {
1472 r = sd_bus_message_append(m, "v", "a(st)", 0);
1474 const char *path, *bandwidth, *e;
1477 e = strchr(eq, ' ');
1479 path = strndupa(eq, e - eq);
1482 log_error("Failed to parse %s value %s.", field, eq);
1486 if (!path_startswith(path, "/dev")) {
1487 log_error("%s is not a device file in /dev.", path);
1491 r = parse_size(bandwidth, 1000, &bytes);
1493 log_error("Failed to parse byte value %s.", bandwidth);
1497 r = sd_bus_message_append(m, "v", "a(st)", 1, path, (uint64_t) bytes);
1500 } else if (streq(field, "BlockIODeviceWeight")) {
1503 r = sd_bus_message_append(m, "v", "a(st)", 0);
1505 const char *path, *weight, *e;
1508 e = strchr(eq, ' ');
1510 path = strndupa(eq, e - eq);
1513 log_error("Failed to parse %s value %s.", field, eq);
1517 if (!path_startswith(path, "/dev")) {
1518 log_error("%s is not a device file in /dev.", path);
1522 r = safe_atou64(weight, &u);
1524 log_error("Failed to parse %s value %s.", field, weight);
1527 r = sd_bus_message_append(m, "v", "a(st)", path, u);
1530 } else if (rlimit_from_string(field) >= 0) {
1533 if (streq(eq, "infinity"))
1536 r = safe_atou64(eq, &rl);
1538 log_error("Invalid resource limit: %s", eq);
1543 r = sd_bus_message_append(m, "v", "t", rl);
1545 } else if (streq(field, "Nice")) {
1548 r = safe_atoi32(eq, &i);
1550 log_error("Failed to parse %s value %s.", field, eq);
1554 r = sd_bus_message_append(m, "v", "i", i);
1556 } else if (streq(field, "Environment")) {
1558 r = sd_bus_message_append(m, "v", "as", 1, eq);
1560 } else if (streq(field, "KillSignal")) {
1563 sig = signal_from_string_try_harder(eq);
1565 log_error("Failed to parse %s value %s.", field, eq);
1569 r = sd_bus_message_append(m, "v", "i", sig);
1571 } else if (streq(field, "AccuracySec")) {
1574 r = parse_sec(eq, &u);
1576 log_error("Failed to parse %s value %s", field, eq);
1580 r = sd_bus_message_append(m, "v", "t", u);
1583 log_error("Unknown assignment %s.", assignment);
1588 return bus_log_create_error(r);
1593 typedef struct BusWaitForJobs {
1600 sd_bus_slot *slot_job_removed;
1601 sd_bus_slot *slot_disconnected;
1604 static int match_disconnected(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1607 log_error("Warning! D-Bus connection terminated.");
1608 sd_bus_close(sd_bus_message_get_bus(m));
1613 static int match_job_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1614 const char *path, *unit, *result;
1615 BusWaitForJobs *d = userdata;
1623 r = sd_bus_message_read(m, "uoss", &id, &path, &unit, &result);
1625 bus_log_parse_error(r);
1629 found = set_remove(d->jobs, (char*) path);
1635 if (!isempty(result))
1636 d->result = strdup(result);
1639 d->name = strdup(unit);
1644 void bus_wait_for_jobs_free(BusWaitForJobs *d) {
1648 set_free_free(d->jobs);
1650 sd_bus_slot_unref(d->slot_disconnected);
1651 sd_bus_slot_unref(d->slot_job_removed);
1653 sd_bus_unref(d->bus);
1661 int bus_wait_for_jobs_new(sd_bus *bus, BusWaitForJobs **ret) {
1662 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *d = NULL;
1668 d = new0(BusWaitForJobs, 1);
1672 d->bus = sd_bus_ref(bus);
1674 /* When we are a bus client we match by sender. Direct
1675 * connections OTOH have no initialized sender field, and
1676 * hence we ignore the sender then */
1677 r = sd_bus_add_match(
1679 &d->slot_job_removed,
1682 "sender='org.freedesktop.systemd1',"
1683 "interface='org.freedesktop.systemd1.Manager',"
1684 "member='JobRemoved',"
1685 "path='/org/freedesktop/systemd1'" :
1687 "interface='org.freedesktop.systemd1.Manager',"
1688 "member='JobRemoved',"
1689 "path='/org/freedesktop/systemd1'",
1690 match_job_removed, d);
1694 r = sd_bus_add_match(
1696 &d->slot_disconnected,
1698 "sender='org.freedesktop.DBus.Local',"
1699 "interface='org.freedesktop.DBus.Local',"
1700 "member='Disconnected'",
1701 match_disconnected, d);
1711 static int bus_process_wait(sd_bus *bus) {
1715 r = sd_bus_process(bus, NULL);
1721 r = sd_bus_wait(bus, (uint64_t) -1);
1727 static int bus_job_get_service_result(BusWaitForJobs *d, char **result) {
1728 _cleanup_free_ char *dbus_path = NULL;
1734 dbus_path = unit_dbus_path_from_name(d->name);
1738 return sd_bus_get_property_string(d->bus,
1739 "org.freedesktop.systemd1",
1741 "org.freedesktop.systemd1.Service",
1747 static const struct {
1748 const char *result, *explanation;
1749 } explanations [] = {
1750 { "resources", "a configured resource limit was exceeded" },
1751 { "timeout", "a timeout was exceeded" },
1752 { "exit-code", "the control process exited with error code" },
1753 { "signal", "a fatal signal was delivered to the control process" },
1754 { "core-dump", "a fatal signal was delivered causing the control process to dump core" },
1755 { "watchdog", "the service failed to send watchdog ping" },
1756 { "start-limit", "start of the service was attempted too often" }
1759 static void log_job_error_with_service_result(const char* service, const char *result) {
1760 _cleanup_free_ char *service_shell_quoted = NULL;
1764 service_shell_quoted = shell_maybe_quote(service);
1766 if (!isempty(result)) {
1769 for (i = 0; i < ELEMENTSOF(explanations); ++i)
1770 if (streq(result, explanations[i].result))
1773 if (i < ELEMENTSOF(explanations)) {
1774 log_error("Job for %s failed because %s. See \"systemctl status %s\" and \"journalctl -xe\" for details.\n",
1776 explanations[i].explanation,
1777 strna(service_shell_quoted));
1783 log_error("Job for %s failed. See \"systemctl status %s\" and \"journalctl -xe\" for details.\n",
1785 strna(service_shell_quoted));
1788 /* For some results maybe additional explanation is required */
1789 if (streq_ptr(result, "start-limit"))
1790 log_info("To force a start use \"systemctl reset-failed %1$s\" followed by \"systemctl start %1$s\" again.",
1791 strna(service_shell_quoted));
1794 static int check_wait_response(BusWaitForJobs *d, bool quiet) {
1800 if (streq(d->result, "canceled"))
1801 log_error("Job for %s canceled.", strna(d->name));
1802 else if (streq(d->result, "timeout"))
1803 log_error("Job for %s timed out.", strna(d->name));
1804 else if (streq(d->result, "dependency"))
1805 log_error("A dependency job for %s failed. See 'journalctl -xe' for details.", strna(d->name));
1806 else if (streq(d->result, "invalid"))
1807 log_error("Job for %s invalid.", strna(d->name));
1808 else if (streq(d->result, "assert"))
1809 log_error("Assertion failed on job for %s.", strna(d->name));
1810 else if (streq(d->result, "unsupported"))
1811 log_error("Operation on or unit type of %s not supported on this system.", strna(d->name));
1812 else if (!streq(d->result, "done") && !streq(d->result, "skipped")) {
1815 _cleanup_free_ char *result = NULL;
1817 q = bus_job_get_service_result(d, &result);
1819 log_debug_errno(q, "Failed to get Result property of service %s: %m", d->name);
1821 log_job_error_with_service_result(d->name, result);
1823 log_error("Job failed. See \"journalctl -xe\" for details.");
1827 if (streq(d->result, "canceled"))
1829 else if (streq(d->result, "timeout"))
1831 else if (streq(d->result, "dependency"))
1833 else if (streq(d->result, "invalid"))
1835 else if (streq(d->result, "assert"))
1837 else if (streq(d->result, "unsupported"))
1839 else if (!streq(d->result, "done") && !streq(d->result, "skipped"))
1845 int bus_wait_for_jobs(BusWaitForJobs *d, bool quiet) {
1850 while (!set_isempty(d->jobs)) {
1853 q = bus_process_wait(d->bus);
1855 return log_error_errno(q, "Failed to wait for response: %m");
1858 q = check_wait_response(d, quiet);
1859 /* Return the first error as it is most likely to be
1861 if (q < 0 && r == 0)
1864 log_debug_errno(q, "Got result %s/%m for job %s", strna(d->result), strna(d->name));
1877 int bus_wait_for_jobs_add(BusWaitForJobs *d, const char *path) {
1882 r = set_ensure_allocated(&d->jobs, &string_hash_ops);
1886 return set_put_strdup(d->jobs, path);
1889 int bus_deserialize_and_dump_unit_file_changes(sd_bus_message *m, bool quiet, UnitFileChange **changes, unsigned *n_changes) {
1890 const char *type, *path, *source;
1893 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sss)");
1895 return bus_log_parse_error(r);
1897 while ((r = sd_bus_message_read(m, "(sss)", &type, &path, &source)) > 0) {
1899 if (streq(type, "symlink"))
1900 log_info("Created symlink from %s to %s.", path, source);
1902 log_info("Removed symlink %s.", path);
1905 r = unit_file_changes_add(changes, n_changes, streq(type, "symlink") ? UNIT_FILE_SYMLINK : UNIT_FILE_UNLINK, path, source);
1910 return bus_log_parse_error(r);
1912 r = sd_bus_message_exit_container(m);
1914 return bus_log_parse_error(r);
1920 * bus_path_encode_unique() - encode unique object path
1921 * @b: bus connection or NULL
1922 * @prefix: object path prefix
1923 * @sender_id: unique-name of client, or NULL
1924 * @external_id: external ID to be chosen by client, or NULL
1925 * @ret_path: storage for encoded object path pointer
1927 * Whenever we provide a bus API that allows clients to create and manage
1928 * server-side objects, we need to provide a unique name for these objects. If
1929 * we let the server choose the name, we suffer from a race condition: If a
1930 * client creates an object asynchronously, it cannot destroy that object until
1931 * it received the method reply. It cannot know the name of the new object,
1932 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
1934 * Therefore, many APIs allow the client to choose the unique name for newly
1935 * created objects. There're two problems to solve, though:
1936 * 1) Object names are usually defined via dbus object paths, which are
1937 * usually globally namespaced. Therefore, multiple clients must be able
1938 * to choose unique object names without interference.
1939 * 2) If multiple libraries share the same bus connection, they must be
1940 * able to choose unique object names without interference.
1941 * The first problem is solved easily by prefixing a name with the
1942 * unique-bus-name of a connection. The server side must enforce this and
1943 * reject any other name. The second problem is solved by providing unique
1944 * suffixes from within sd-bus.
1946 * This helper allows clients to create unique object-paths. It uses the
1947 * template '/prefix/sender_id/external_id' and returns the new path in
1948 * @ret_path (must be freed by the caller).
1949 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
1950 * NULL, this function allocates a unique suffix via @b (by requesting a new
1951 * cookie). If both @sender_id and @external_id are given, @b can be passed as
1954 * Returns: 0 on success, negative error code on failure.
1956 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
1957 _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
1958 char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
1961 assert_return(b || (sender_id && external_id), -EINVAL);
1962 assert_return(object_path_is_valid(prefix), -EINVAL);
1963 assert_return(ret_path, -EINVAL);
1966 r = sd_bus_get_unique_name(b, &sender_id);
1972 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
1973 external_id = external_buf;
1976 sender_label = bus_label_escape(sender_id);
1980 external_label = bus_label_escape(external_id);
1981 if (!external_label)
1984 p = strjoin(prefix, "/", sender_label, "/", external_label, NULL);
1993 * bus_path_decode_unique() - decode unique object path
1994 * @path: object path to decode
1995 * @prefix: object path prefix
1996 * @ret_sender: output parameter for sender-id label
1997 * @ret_external: output parameter for external-id label
1999 * This does the reverse of bus_path_encode_unique() (see its description for
2000 * details). Both trailing labels, sender-id and external-id, are unescaped and
2001 * returned in the given output parameters (the caller must free them).
2003 * Note that this function returns 0 if the path does not match the template
2004 * (see bus_path_encode_unique()), 1 if it matched.
2006 * Returns: Negative error code on failure, 0 if the given object path does not
2007 * match the template (return parameters are set to NULL), 1 if it was
2008 * parsed successfully (return parameters contain allocated labels).
2010 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
2012 char *sender, *external;
2014 assert(object_path_is_valid(path));
2015 assert(object_path_is_valid(prefix));
2017 assert(ret_external);
2019 p = object_path_startswith(path, prefix);
2022 *ret_external = NULL;
2029 *ret_external = NULL;
2033 sender = bus_label_unescape_n(p, q - p);
2034 external = bus_label_unescape(q + 1);
2035 if (!sender || !external) {
2041 *ret_sender = sender;
2042 *ret_external = external;
2046 bool is_kdbus_wanted(void) {
2047 _cleanup_free_ char *value = NULL;
2049 const bool configured = true;
2051 const bool configured = false;
2056 if (get_proc_cmdline_key("kdbus", NULL) > 0)
2059 r = get_proc_cmdline_key("kdbus=", &value);
2063 return parse_boolean(value) == 1;
2066 bool is_kdbus_available(void) {
2067 _cleanup_close_ int fd = -1;
2068 struct kdbus_cmd cmd = { .size = sizeof(cmd), .flags = KDBUS_FLAG_NEGOTIATE };
2070 if (!is_kdbus_wanted())
2073 fd = open("/sys/fs/kdbus/control", O_RDWR | O_CLOEXEC | O_NONBLOCK | O_NOCTTY);
2077 return ioctl(fd, KDBUS_CMD_BUS_MAKE, &cmd) >= 0;