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 "unit-name.h"
36 #include "bus-error.h"
37 #include "bus-label.h"
38 #include "bus-message.h"
40 #include "bus-internal.h"
42 static int name_owner_change_callback(sd_bus *bus, sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
43 sd_event *e = userdata;
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 r = sd_bus_creds_get_euid(creds, &sender_uid);
213 return sender_uid == good_user;
217 sd_bus_message *call,
229 /* Tests non-interactively! */
231 r = check_good_user(call, good_user);
235 r = sd_bus_query_sender_privilege(call, capability);
242 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
243 int authorized = false, challenge = false;
246 sender = sd_bus_message_get_sender(call);
250 r = sd_bus_call_method(
252 "org.freedesktop.PolicyKit1",
253 "/org/freedesktop/PolicyKit1/Authority",
254 "org.freedesktop.PolicyKit1.Authority",
255 "CheckAuthorization",
259 "system-bus-name", 1, "name", "s", sender,
266 /* Treat no PK available as access denied */
267 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN)) {
268 sd_bus_error_free(e);
275 r = sd_bus_message_enter_container(reply, 'r', "bba{ss}");
279 r = sd_bus_message_read(reply, "bb", &authorized, &challenge);
287 *_challenge = challenge;
298 typedef struct AsyncPolkitQuery {
299 sd_bus_message *request, *reply;
300 sd_bus_message_handler_t callback;
306 static void async_polkit_query_free(AsyncPolkitQuery *q) {
311 sd_bus_slot_unref(q->slot);
313 if (q->registry && q->request)
314 hashmap_remove(q->registry, q->request);
316 sd_bus_message_unref(q->request);
317 sd_bus_message_unref(q->reply);
322 static int async_polkit_callback(sd_bus *bus, sd_bus_message *reply, void *userdata, sd_bus_error *error) {
323 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
324 AsyncPolkitQuery *q = userdata;
331 q->slot = sd_bus_slot_unref(q->slot);
332 q->reply = sd_bus_message_ref(reply);
334 r = sd_bus_message_rewind(q->request, true);
336 r = sd_bus_reply_method_errno(q->request, r, NULL);
340 r = q->callback(bus, q->request, q->userdata, &error_buffer);
341 r = bus_maybe_reply_error(q->request, r, &error_buffer);
344 async_polkit_query_free(q);
351 int bus_verify_polkit_async(
352 sd_bus_message *call,
358 sd_bus_error *error) {
361 _cleanup_bus_message_unref_ sd_bus_message *pk = NULL;
364 sd_bus_message_handler_t callback;
374 r = check_good_user(call, good_user);
379 q = hashmap_get(*registry, call);
381 int authorized, challenge;
383 /* This is the second invocation of this function, and
384 * there's already a response from polkit, let's
388 if (sd_bus_message_is_method_error(q->reply, NULL)) {
389 const sd_bus_error *e;
391 /* Copy error from polkit reply */
392 e = sd_bus_message_get_error(q->reply);
393 sd_bus_error_copy(error, e);
395 /* Treat no PK available as access denied */
396 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN))
399 return -sd_bus_error_get_errno(e);
402 r = sd_bus_message_enter_container(q->reply, 'r', "bba{ss}");
404 r = sd_bus_message_read(q->reply, "bb", &authorized, &challenge);
413 return sd_bus_error_set(error, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED, "Interactive authentication required.");
419 r = sd_bus_query_sender_privilege(call, capability);
426 if (sd_bus_get_current_message(call->bus) != call)
429 callback = sd_bus_get_current_handler(call->bus);
433 userdata = sd_bus_get_current_userdata(call->bus);
435 sender = sd_bus_message_get_sender(call);
439 c = sd_bus_message_get_allow_interactive_authorization(call);
445 r = hashmap_ensure_allocated(registry, NULL);
449 r = sd_bus_message_new_method_call(
452 "org.freedesktop.PolicyKit1",
453 "/org/freedesktop/PolicyKit1/Authority",
454 "org.freedesktop.PolicyKit1.Authority",
455 "CheckAuthorization");
459 r = sd_bus_message_append(
462 "system-bus-name", 1, "name", "s", sender,
470 q = new0(AsyncPolkitQuery, 1);
474 q->request = sd_bus_message_ref(call);
475 q->callback = callback;
476 q->userdata = userdata;
478 r = hashmap_put(*registry, call, q);
480 async_polkit_query_free(q);
484 q->registry = *registry;
486 r = sd_bus_call_async(call->bus, &q->slot, pk, async_polkit_callback, q, 0);
488 async_polkit_query_free(q);
498 void bus_verify_polkit_async_registry_free(Hashmap *registry) {
502 while ((q = hashmap_steal_first(registry)))
503 async_polkit_query_free(q);
505 hashmap_free(registry);
509 int bus_check_peercred(sd_bus *c) {
516 fd = sd_bus_get_fd(c);
520 l = sizeof(struct ucred);
521 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
524 if (l != sizeof(struct ucred))
527 if (ucred.uid != 0 && ucred.uid != geteuid())
533 int bus_open_system_systemd(sd_bus **_bus) {
534 _cleanup_bus_unref_ sd_bus *bus = NULL;
540 return sd_bus_open_system(_bus);
542 /* If we are root and kdbus is not available, then let's talk
543 * directly to the system instance, instead of going via the
547 r = sd_bus_new(&bus);
551 r = sd_bus_set_address(bus, KERNEL_SYSTEM_BUS_ADDRESS);
555 bus->bus_client = true;
557 r = sd_bus_start(bus);
564 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 */
600 r = sd_bus_new(&bus);
604 if (asprintf(&bus->address, KERNEL_USER_BUS_ADDRESS_FMT, getuid()) < 0)
607 bus->bus_client = true;
609 r = sd_bus_start(bus);
616 bus = sd_bus_unref(bus);
619 e = secure_getenv("XDG_RUNTIME_DIR");
621 return sd_bus_open_user(_bus);
623 ee = bus_address_escape(e);
627 r = sd_bus_new(&bus);
631 bus->address = strjoin("unix:path=", ee, "/systemd/private", NULL);
635 r = sd_bus_start(bus);
637 return sd_bus_open_user(_bus);
639 r = bus_check_peercred(bus);
649 int bus_print_property(const char *name, sd_bus_message *property, bool all) {
651 const char *contents;
657 r = sd_bus_message_peek_type(property, &type, &contents);
663 case SD_BUS_TYPE_STRING: {
666 r = sd_bus_message_read_basic(property, type, &s);
670 if (all || !isempty(s)) {
671 _cleanup_free_ char *escaped = NULL;
673 escaped = xescape(s, "\n");
677 printf("%s=%s\n", name, escaped);
683 case SD_BUS_TYPE_BOOLEAN: {
686 r = sd_bus_message_read_basic(property, type, &b);
690 printf("%s=%s\n", name, yes_no(b));
695 case SD_BUS_TYPE_UINT64: {
698 r = sd_bus_message_read_basic(property, type, &u);
702 /* Yes, heuristics! But we can change this check
703 * should it turn out to not be sufficient */
705 if (endswith(name, "Timestamp")) {
706 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
708 t = format_timestamp(timestamp, sizeof(timestamp), u);
710 printf("%s=%s\n", name, strempty(t));
712 } else if (strstr(name, "USec")) {
713 char timespan[FORMAT_TIMESPAN_MAX];
715 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u, 0));
717 printf("%s=%llu\n", name, (unsigned long long) u);
722 case SD_BUS_TYPE_INT64: {
725 r = sd_bus_message_read_basic(property, type, &i);
729 printf("%s=%lld\n", name, (long long) i);
734 case SD_BUS_TYPE_UINT32: {
737 r = sd_bus_message_read_basic(property, type, &u);
741 if (strstr(name, "UMask") || strstr(name, "Mode"))
742 printf("%s=%04o\n", name, u);
744 printf("%s=%u\n", name, (unsigned) u);
749 case SD_BUS_TYPE_INT32: {
752 r = sd_bus_message_read_basic(property, type, &i);
756 printf("%s=%i\n", name, (int) i);
760 case SD_BUS_TYPE_DOUBLE: {
763 r = sd_bus_message_read_basic(property, type, &d);
767 printf("%s=%g\n", name, d);
771 case SD_BUS_TYPE_ARRAY:
772 if (streq(contents, "s")) {
776 r = sd_bus_message_enter_container(property, SD_BUS_TYPE_ARRAY, contents);
780 while((r = sd_bus_message_read_basic(property, SD_BUS_TYPE_STRING, &str)) > 0) {
781 _cleanup_free_ char *escaped = NULL;
786 escaped = xescape(str, "\n ");
790 printf("%s%s", first ? "" : " ", escaped);
802 r = sd_bus_message_exit_container(property);
808 } else if (streq(contents, "y")) {
812 r = sd_bus_message_read_array(property, SD_BUS_TYPE_BYTE, (const void**) &u, &n);
821 for (i = 0; i < n; i++)
822 printf("%02x", u[i]);
829 } else if (streq(contents, "u")) {
833 r = sd_bus_message_read_array(property, SD_BUS_TYPE_UINT32, (const void**) &u, &n);
842 for (i = 0; i < n; i++)
843 printf("%08x", u[i]);
857 int bus_print_all_properties(sd_bus *bus, const char *dest, const char *path, char **filter, bool all) {
858 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
859 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
865 r = sd_bus_call_method(bus,
868 "org.freedesktop.DBus.Properties",
876 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "{sv}");
880 while ((r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
882 const char *contents;
884 r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &name);
888 if (!filter || strv_find(filter, name)) {
889 r = sd_bus_message_peek_type(reply, NULL, &contents);
893 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_VARIANT, contents);
897 r = bus_print_property(name, reply, all);
902 printf("%s=[unprintable]\n", name);
903 /* skip what we didn't read */
904 r = sd_bus_message_skip(reply, contents);
909 r = sd_bus_message_exit_container(reply);
913 r = sd_bus_message_skip(reply, "v");
918 r = sd_bus_message_exit_container(reply);
925 r = sd_bus_message_exit_container(reply);
932 int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
933 sd_id128_t *p = userdata;
938 r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n);
945 memcpy((*p).bytes, v, n);
952 static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
956 r = sd_bus_message_peek_type(m, &type, NULL);
961 case SD_BUS_TYPE_STRING: {
965 r = sd_bus_message_read_basic(m, type, &s);
972 r = free_and_strdup(p, s);
976 case SD_BUS_TYPE_ARRAY: {
977 _cleanup_strv_free_ char **l = NULL;
978 char ***p = userdata;
980 r = bus_message_read_strv_extend(m, &l);
991 case SD_BUS_TYPE_BOOLEAN: {
995 r = sd_bus_message_read_basic(m, type, &b);
1004 case SD_BUS_TYPE_UINT32: {
1006 uint32_t *p = userdata;
1008 r = sd_bus_message_read_basic(m, type, &u);
1017 case SD_BUS_TYPE_UINT64: {
1019 uint64_t *p = userdata;
1021 r = sd_bus_message_read_basic(m, type, &t);
1037 int bus_message_map_all_properties(sd_bus *bus,
1039 const struct bus_properties_map *map,
1041 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1048 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
1052 while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1053 const struct bus_properties_map *prop;
1055 const char *contents;
1059 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
1063 for (i = 0, prop = NULL; map[i].member; i++)
1064 if (streq(map[i].member, member)) {
1070 r = sd_bus_message_peek_type(m, NULL, &contents);
1074 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
1078 v = (uint8_t *)userdata + prop->offset;
1080 r = prop->set(bus, member, m, &error, v);
1082 r = map_basic(bus, member, m, &error, v);
1086 r = sd_bus_message_exit_container(m);
1090 r = sd_bus_message_skip(m, "v");
1095 r = sd_bus_message_exit_container(m);
1100 return sd_bus_message_exit_container(m);
1103 int bus_message_map_properties_changed(sd_bus *bus,
1105 const struct bus_properties_map *map,
1108 int r, invalidated, i;
1114 r = bus_message_map_all_properties(bus, 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)) {
1130 r = sd_bus_message_exit_container(m);
1137 int bus_map_all_properties(sd_bus *bus,
1138 const char *destination,
1140 const struct bus_properties_map *map,
1142 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
1143 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1147 assert(destination);
1151 r = sd_bus_call_method(
1155 "org.freedesktop.DBus.Properties",
1163 return bus_message_map_all_properties(bus, m, map, userdata);
1166 int bus_open_transport(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1169 assert(transport >= 0);
1170 assert(transport < _BUS_TRANSPORT_MAX);
1173 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1174 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1176 switch (transport) {
1178 case BUS_TRANSPORT_LOCAL:
1180 r = sd_bus_default_user(bus);
1182 r = sd_bus_default_system(bus);
1186 case BUS_TRANSPORT_REMOTE:
1187 r = sd_bus_open_system_remote(bus, host);
1190 case BUS_TRANSPORT_MACHINE:
1191 r = sd_bus_open_system_machine(bus, host);
1195 assert_not_reached("Hmm, unknown transport type.");
1201 int bus_open_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1204 assert(transport >= 0);
1205 assert(transport < _BUS_TRANSPORT_MAX);
1208 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1209 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1211 switch (transport) {
1213 case BUS_TRANSPORT_LOCAL:
1215 r = bus_open_user_systemd(bus);
1217 r = bus_open_system_systemd(bus);
1221 case BUS_TRANSPORT_REMOTE:
1222 r = sd_bus_open_system_remote(bus, host);
1225 case BUS_TRANSPORT_MACHINE:
1226 r = sd_bus_open_system_machine(bus, host);
1230 assert_not_reached("Hmm, unknown transport type.");
1236 int bus_property_get_bool(
1239 const char *interface,
1240 const char *property,
1241 sd_bus_message *reply,
1243 sd_bus_error *error) {
1245 int b = *(bool*) userdata;
1247 return sd_bus_message_append_basic(reply, 'b', &b);
1250 #if __SIZEOF_SIZE_T__ != 8
1251 int bus_property_get_size(
1254 const char *interface,
1255 const char *property,
1256 sd_bus_message *reply,
1258 sd_bus_error *error) {
1260 uint64_t sz = *(size_t*) userdata;
1262 return sd_bus_message_append_basic(reply, 't', &sz);
1266 #if __SIZEOF_LONG__ != 8
1267 int bus_property_get_long(
1270 const char *interface,
1271 const char *property,
1272 sd_bus_message *reply,
1274 sd_bus_error *error) {
1276 int64_t l = *(long*) userdata;
1278 return sd_bus_message_append_basic(reply, 'x', &l);
1281 int bus_property_get_ulong(
1284 const char *interface,
1285 const char *property,
1286 sd_bus_message *reply,
1288 sd_bus_error *error) {
1290 uint64_t ul = *(unsigned long*) userdata;
1292 return sd_bus_message_append_basic(reply, 't', &ul);
1296 int bus_log_parse_error(int r) {
1297 return log_error_errno(r, "Failed to parse bus message: %m");
1300 int bus_log_create_error(int r) {
1301 return log_error_errno(r, "Failed to create bus message: %m");
1304 int bus_parse_unit_info(sd_bus_message *message, UnitInfo *u) {
1310 return sd_bus_message_read(
1325 int bus_maybe_reply_error(sd_bus_message *m, int r, sd_bus_error *error) {
1329 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL)
1330 sd_bus_reply_method_errno(m, r, error);
1332 } else if (sd_bus_error_is_set(error)) {
1333 if (m->header->type == SD_BUS_MESSAGE_METHOD_CALL)
1334 sd_bus_reply_method_error(m, error);
1338 log_debug("Failed to process message [type=%s sender=%s path=%s interface=%s member=%s signature=%s]: %s",
1339 bus_message_type_to_string(m->header->type),
1342 strna(m->interface),
1344 strna(m->root_container.signature),
1345 bus_error_message(error, r));
1350 int bus_append_unit_property_assignment(sd_bus_message *m, const char *assignment) {
1351 const char *eq, *field;
1357 eq = strchr(assignment, '=');
1359 log_error("Not an assignment: %s", assignment);
1363 field = strndupa(assignment, eq - assignment);
1366 if (streq(field, "CPUQuota")) {
1370 r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, "CPUQuotaPerSecUSec");
1372 return bus_log_create_error(r);
1374 r = sd_bus_message_append(m, "v", "t", USEC_INFINITY);
1376 } else if (endswith(eq, "%")) {
1379 if (sscanf(eq, "%lf%%", &percent) != 1 || percent <= 0) {
1380 log_error("CPU quota '%s' invalid.", eq);
1384 r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, "CPUQuotaPerSecUSec");
1386 return bus_log_create_error(r);
1388 r = sd_bus_message_append(m, "v", "t", (usec_t) percent * USEC_PER_SEC / 100);
1390 log_error("CPU quota needs to be in percent.");
1395 return bus_log_create_error(r);
1400 r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, field);
1402 return bus_log_create_error(r);
1404 if (STR_IN_SET(field,
1405 "CPUAccounting", "MemoryAccounting", "BlockIOAccounting",
1406 "SendSIGHUP", "SendSIGKILL", "WakeSystem", "DefaultDependencies")) {
1408 r = parse_boolean(eq);
1410 log_error("Failed to parse boolean assignment %s.", assignment);
1414 r = sd_bus_message_append(m, "v", "b", r);
1416 } else if (streq(field, "MemoryLimit")) {
1419 r = parse_size(eq, 1024, &bytes);
1421 log_error("Failed to parse bytes specification %s", assignment);
1425 r = sd_bus_message_append(m, "v", "t", (uint64_t) bytes);
1427 } else if (STR_IN_SET(field, "CPUShares", "BlockIOWeight")) {
1430 r = safe_atou64(eq, &u);
1432 log_error("Failed to parse %s value %s.", field, eq);
1436 r = sd_bus_message_append(m, "v", "t", u);
1438 } else if (STR_IN_SET(field, "User", "Group", "DevicePolicy", "KillMode"))
1439 r = sd_bus_message_append(m, "v", "s", eq);
1441 else if (streq(field, "DeviceAllow")) {
1444 r = sd_bus_message_append(m, "v", "a(ss)", 0);
1446 const char *path, *rwm, *e;
1448 e = strchr(eq, ' ');
1450 path = strndupa(eq, e - eq);
1457 if (!path_startswith(path, "/dev")) {
1458 log_error("%s is not a device file in /dev.", path);
1462 r = sd_bus_message_append(m, "v", "a(ss)", 1, path, rwm);
1465 } else if (STR_IN_SET(field, "BlockIOReadBandwidth", "BlockIOWriteBandwidth")) {
1468 r = sd_bus_message_append(m, "v", "a(st)", 0);
1470 const char *path, *bandwidth, *e;
1473 e = strchr(eq, ' ');
1475 path = strndupa(eq, e - eq);
1478 log_error("Failed to parse %s value %s.", field, eq);
1482 if (!path_startswith(path, "/dev")) {
1483 log_error("%s is not a device file in /dev.", path);
1487 r = parse_size(bandwidth, 1000, &bytes);
1489 log_error("Failed to parse byte value %s.", bandwidth);
1493 r = sd_bus_message_append(m, "v", "a(st)", 1, path, (uint64_t) bytes);
1496 } else if (streq(field, "BlockIODeviceWeight")) {
1499 r = sd_bus_message_append(m, "v", "a(st)", 0);
1501 const char *path, *weight, *e;
1504 e = strchr(eq, ' ');
1506 path = strndupa(eq, e - eq);
1509 log_error("Failed to parse %s value %s.", field, eq);
1513 if (!path_startswith(path, "/dev")) {
1514 log_error("%s is not a device file in /dev.", path);
1518 r = safe_atou64(weight, &u);
1520 log_error("Failed to parse %s value %s.", field, weight);
1523 r = sd_bus_message_append(m, "v", "a(st)", path, u);
1526 } else if (rlimit_from_string(field) >= 0) {
1529 if (streq(eq, "infinity"))
1532 r = safe_atou64(eq, &rl);
1534 log_error("Invalid resource limit: %s", eq);
1539 r = sd_bus_message_append(m, "v", "t", rl);
1541 } else if (streq(field, "Nice")) {
1544 r = safe_atoi32(eq, &i);
1546 log_error("Failed to parse %s value %s.", field, eq);
1550 r = sd_bus_message_append(m, "v", "i", i);
1552 } else if (streq(field, "Environment")) {
1554 r = sd_bus_message_append(m, "v", "as", 1, eq);
1556 } else if (streq(field, "KillSignal")) {
1559 sig = signal_from_string_try_harder(eq);
1561 log_error("Failed to parse %s value %s.", field, eq);
1565 r = sd_bus_message_append(m, "v", "i", sig);
1567 } else if (streq(field, "AccuracySec")) {
1570 r = parse_sec(eq, &u);
1572 log_error("Failed to parse %s value %s", field, eq);
1576 r = sd_bus_message_append(m, "v", "t", u);
1579 log_error("Unknown assignment %s.", assignment);
1584 return bus_log_create_error(r);
1589 typedef struct BusWaitForJobs {
1596 sd_bus_slot *slot_job_removed;
1597 sd_bus_slot *slot_disconnected;
1600 static int match_disconnected(sd_bus *bus, sd_bus_message *m, void *userdata, sd_bus_error *error) {
1604 log_error("Warning! D-Bus connection terminated.");
1610 static int match_job_removed(sd_bus *bus, sd_bus_message *m, void *userdata, sd_bus_error *error) {
1611 const char *path, *unit, *result;
1612 BusWaitForJobs *d = userdata;
1621 r = sd_bus_message_read(m, "uoss", &id, &path, &unit, &result);
1623 bus_log_parse_error(r);
1627 found = set_remove(d->jobs, (char*) path);
1633 if (!isempty(result))
1634 d->result = strdup(result);
1637 d->name = strdup(unit);
1642 void bus_wait_for_jobs_free(BusWaitForJobs *d) {
1646 set_free_free(d->jobs);
1648 sd_bus_slot_unref(d->slot_disconnected);
1649 sd_bus_slot_unref(d->slot_job_removed);
1651 sd_bus_unref(d->bus);
1659 int bus_wait_for_jobs_new(sd_bus *bus, BusWaitForJobs **ret) {
1660 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *d = NULL;
1666 d = new0(BusWaitForJobs, 1);
1670 d->bus = sd_bus_ref(bus);
1672 /* When we are a bus client we match by sender. Direct
1673 * connections OTOH have no initialized sender field, and
1674 * hence we ignore the sender then */
1675 r = sd_bus_add_match(
1677 &d->slot_job_removed,
1680 "sender='org.freedesktop.systemd1',"
1681 "interface='org.freedesktop.systemd1.Manager',"
1682 "member='JobRemoved',"
1683 "path='/org/freedesktop/systemd1'" :
1685 "interface='org.freedesktop.systemd1.Manager',"
1686 "member='JobRemoved',"
1687 "path='/org/freedesktop/systemd1'",
1688 match_job_removed, d);
1692 r = sd_bus_add_match(
1694 &d->slot_disconnected,
1696 "sender='org.freedesktop.DBus.Local',"
1697 "interface='org.freedesktop.DBus.Local',"
1698 "member='Disconnected'",
1699 match_disconnected, d);
1709 static int bus_process_wait(sd_bus *bus) {
1713 r = sd_bus_process(bus, NULL);
1719 r = sd_bus_wait(bus, (uint64_t) -1);
1725 static int bus_job_get_service_result(BusWaitForJobs *d, char **result) {
1726 _cleanup_free_ char *dbus_path = NULL;
1732 dbus_path = unit_dbus_path_from_name(d->name);
1736 return sd_bus_get_property_string(d->bus,
1737 "org.freedesktop.systemd1",
1739 "org.freedesktop.systemd1.Service",
1745 static const struct {
1746 const char *result, *explanation;
1747 } explanations [] = {
1748 { "resources", "configured resource limit was exceeded" },
1749 { "timeout", "timeout was exceeded" },
1750 { "exit-code", "control process exited with error code" },
1751 { "signal", "fatal signal was delivered to the control process" },
1752 { "core-dump", "fatal signal was delivered to the control process. Core dumped" },
1753 { "watchdog", "service failed to send watchdog ping" },
1754 { "start-limit", "start of the service was attempted too often too quickly" }
1757 static void log_job_error_with_service_result(const char* service, const char *result) {
1759 _cleanup_free_ char *service_shell_quoted = NULL;
1764 service_shell_quoted = shell_maybe_quote(service);
1766 for (i = 0; i < ELEMENTSOF(explanations); ++i)
1767 if (streq(result, explanations[i].result))
1770 if (i < ELEMENTSOF(explanations))
1771 log_error("Job for %s failed because %s. See \"systemctl status %s\" and \"journalctl -xe\" for details.\n",
1773 explanations[i].explanation,
1774 strna(service_shell_quoted));
1776 log_error("Job for %s failed. See \"systemctl status %s\" and \"journalctl -xe\" for details.\n",
1778 strna(service_shell_quoted));
1780 /* For some results maybe additional explanation is required */
1781 if (streq_ptr(result, "start-limit"))
1782 log_info("To force a start please invoke \"systemctl reset-failed %s\" followed by \"systemctl start %s\" again.",
1783 strna(service_shell_quoted),
1784 strna(service_shell_quoted));
1787 static int check_wait_response(BusWaitForJobs *d, bool quiet) {
1793 if (streq(d->result, "canceled"))
1794 log_error("Job for %s canceled.", strna(d->name));
1795 else if (streq(d->result, "timeout"))
1796 log_error("Job for %s timed out.", strna(d->name));
1797 else if (streq(d->result, "dependency"))
1798 log_error("A dependency job for %s failed. See 'journalctl -xe' for details.", strna(d->name));
1799 else if (streq(d->result, "invalid"))
1800 log_error("Job for %s invalid.", strna(d->name));
1801 else if (streq(d->result, "assert"))
1802 log_error("Assertion failed on job for %s.", strna(d->name));
1803 else if (streq(d->result, "unsupported"))
1804 log_error("Operation on or unit type of %s not supported on this system.", strna(d->name));
1805 else if (!streq(d->result, "done") && !streq(d->result, "skipped")) {
1808 _cleanup_free_ char *result = NULL;
1810 q = bus_job_get_service_result(d, &result);
1812 log_debug_errno(q, "Failed to get Result property of service %s: %m", d->name);
1814 log_job_error_with_service_result(d->name, result);
1816 log_error("Job failed. See \"journalctl -xe\" for details.");
1820 if (streq(d->result, "canceled"))
1822 else if (streq(d->result, "timeout"))
1824 else if (streq(d->result, "dependency"))
1826 else if (streq(d->result, "invalid"))
1828 else if (streq(d->result, "assert"))
1830 else if (streq(d->result, "unsupported"))
1832 else if (!streq(d->result, "done") && !streq(d->result, "skipped"))
1838 int bus_wait_for_jobs(BusWaitForJobs *d, bool quiet) {
1843 while (!set_isempty(d->jobs)) {
1846 q = bus_process_wait(d->bus);
1848 return log_error_errno(q, "Failed to wait for response: %m");
1851 q = check_wait_response(d, quiet);
1852 /* Return the first error as it is most likely to be
1854 if (q < 0 && r == 0)
1857 log_debug_errno(q, "Got result %s/%m for job %s", strna(d->result), strna(d->name));
1870 int bus_wait_for_jobs_add(BusWaitForJobs *d, const char *path) {
1875 r = set_ensure_allocated(&d->jobs, &string_hash_ops);
1879 return set_put_strdup(d->jobs, path);
1882 int bus_deserialize_and_dump_unit_file_changes(sd_bus_message *m, bool quiet) {
1883 const char *type, *path, *source;
1886 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sss)");
1888 return bus_log_parse_error(r);
1890 while ((r = sd_bus_message_read(m, "(sss)", &type, &path, &source)) > 0) {
1892 if (streq(type, "symlink"))
1893 log_info("Created symlink from %s to %s.", path, source);
1895 log_info("Removed symlink %s.", path);
1899 return bus_log_parse_error(r);
1901 r = sd_bus_message_exit_container(m);
1903 return bus_log_parse_error(r);
1909 * bus_path_encode_unique() - encode unique object path
1910 * @b: bus connection or NULL
1911 * @prefix: object path prefix
1912 * @sender_id: unique-name of client, or NULL
1913 * @external_id: external ID to be chosen by client, or NULL
1914 * @ret_path: storage for encoded object path pointer
1916 * Whenever we provide a bus API that allows clients to create and manage
1917 * server-side objects, we need to provide a unique name for these objects. If
1918 * we let the server choose the name, we suffer from a race condition: If a
1919 * client creates an object asynchronously, it cannot destroy that object until
1920 * it received the method reply. It cannot know the name of the new object,
1921 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
1923 * Therefore, many APIs allow the client to choose the unique name for newly
1924 * created objects. There're two problems to solve, though:
1925 * 1) Object names are usually defined via dbus object paths, which are
1926 * usually globally namespaced. Therefore, multiple clients must be able
1927 * to choose unique object names without interference.
1928 * 2) If multiple libraries share the same bus connection, they must be
1929 * able to choose unique object names without interference.
1930 * The first problem is solved easily by prefixing a name with the
1931 * unique-bus-name of a connection. The server side must enforce this and
1932 * reject any other name. The second problem is solved by providing unique
1933 * suffixes from within sd-bus.
1935 * This helper allows clients to create unique object-paths. It uses the
1936 * template '/prefix/sender_id/external_id' and returns the new path in
1937 * @ret_path (must be freed by the caller).
1938 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
1939 * NULL, this function allocates a unique suffix via @b (by requesting a new
1940 * cookie). If both @sender_id and @external_id are given, @b can be passed as
1943 * Returns: 0 on success, negative error code on failure.
1945 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
1946 _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
1947 char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
1950 assert_return(b || (sender_id && external_id), -EINVAL);
1951 assert_return(object_path_is_valid(prefix), -EINVAL);
1952 assert_return(ret_path, -EINVAL);
1955 r = sd_bus_get_unique_name(b, &sender_id);
1961 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
1962 external_id = external_buf;
1965 sender_label = bus_label_escape(sender_id);
1969 external_label = bus_label_escape(external_id);
1970 if (!external_label)
1973 p = strjoin(prefix, "/", sender_label, "/", external_label, NULL);
1982 * bus_path_decode_unique() - decode unique object path
1983 * @path: object path to decode
1984 * @prefix: object path prefix
1985 * @ret_sender: output parameter for sender-id label
1986 * @ret_external: output parameter for external-id label
1988 * This does the reverse of bus_path_encode_unique() (see its description for
1989 * details). Both trailing labels, sender-id and external-id, are unescaped and
1990 * returned in the given output parameters (the caller must free them).
1992 * Note that this function returns 0 if the path does not match the template
1993 * (see bus_path_encode_unique()), 1 if it matched.
1995 * Returns: Negative error code on failure, 0 if the given object path does not
1996 * match the template (return parameters are set to NULL), 1 if it was
1997 * parsed successfully (return parameters contain allocated labels).
1999 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
2001 char *sender, *external;
2003 assert(object_path_is_valid(path));
2004 assert(object_path_is_valid(prefix));
2006 assert(ret_external);
2008 p = object_path_startswith(path, prefix);
2011 *ret_external = NULL;
2018 *ret_external = NULL;
2022 sender = bus_label_unescape_n(p, q - p);
2023 external = bus_label_unescape(q + 1);
2024 if (!sender || !external) {
2030 *ret_sender = sender;
2031 *ret_external = external;