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>
25 #include "sd-daemon.h"
28 #include "alloc-util.h"
29 #include "bus-error.h"
30 #include "bus-internal.h"
31 #include "bus-label.h"
32 #include "bus-message.h"
34 #include "cgroup-util.h"
36 //#include "env-util.h"
41 #include "parse-util.h"
42 #include "path-util.h"
43 #include "proc-cmdline.h"
44 #include "process-util.h"
45 //#include "rlimit-util.h"
47 #include "signal-util.h"
48 #include "stdio-util.h"
49 #include "string-util.h"
51 #include "syslog-util.h"
52 #include "unit-name.h"
53 #include "user-util.h"
57 #if 0 /// UNNEEDED by elogind
58 static int name_owner_change_callback(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
59 sd_event *e = userdata;
64 sd_bus_close(sd_bus_message_get_bus(m));
70 int bus_async_unregister_and_exit(sd_event *e, sd_bus *bus, const char *name) {
71 _cleanup_free_ char *match = NULL;
79 /* We unregister the name here and then wait for the
80 * NameOwnerChanged signal for this event to arrive before we
81 * quit. We do this in order to make sure that any queued
82 * requests are still processed before we really exit. */
84 r = sd_bus_get_unique_name(bus, &unique);
89 "sender='org.freedesktop.DBus',"
91 "interface='org.freedesktop.DBus',"
92 "member='NameOwnerChanged',"
93 "path='/org/freedesktop/DBus',"
96 "arg2=''", name, unique);
100 r = sd_bus_add_match(bus, NULL, match, name_owner_change_callback, e);
104 r = sd_bus_release_name(bus, name);
111 int bus_event_loop_with_idle(
116 check_idle_t check_idle,
118 bool exiting = false;
128 r = sd_event_get_state(e);
131 if (r == SD_EVENT_FINISHED)
135 idle = check_idle(userdata);
139 r = sd_event_run(e, exiting || !idle ? (uint64_t) -1 : timeout);
143 if (r == 0 && !exiting && idle) {
145 r = sd_bus_try_close(bus);
149 /* Fallback for dbus1 connections: we
150 * unregister the name and wait for the
151 * response to come through for it */
152 if (r == -EOPNOTSUPP) {
154 /* Inform the service manager that we
155 * are going down, so that it will
156 * queue all further start requests,
157 * instead of assuming we are already
159 sd_notify(false, "STOPPING=1");
161 r = bus_async_unregister_and_exit(e, bus, name);
177 r = sd_event_get_exit_code(e, &code);
185 int bus_name_has_owner(sd_bus *c, const char *name, sd_bus_error *error) {
186 _cleanup_bus_message_unref_ sd_bus_message *rep = NULL;
187 int r, has_owner = 0;
192 r = sd_bus_call_method(c,
193 "org.freedesktop.DBus",
194 "/org/freedesktop/dbus",
195 "org.freedesktop.DBus",
204 r = sd_bus_message_read_basic(rep, 'b', &has_owner);
206 return sd_bus_error_set_errno(error, r);
211 static int check_good_user(sd_bus_message *m, uid_t good_user) {
212 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
218 if (good_user == UID_INVALID)
221 r = sd_bus_query_sender_creds(m, SD_BUS_CREDS_EUID, &creds);
225 /* Don't trust augmented credentials for authorization */
226 assert_return((sd_bus_creds_get_augmented_mask(creds) & SD_BUS_CREDS_EUID) == 0, -EPERM);
228 r = sd_bus_creds_get_euid(creds, &sender_uid);
232 return sender_uid == good_user;
236 sd_bus_message *call,
239 const char **details,
249 /* Tests non-interactively! */
251 r = check_good_user(call, good_user);
255 r = sd_bus_query_sender_privilege(call, capability);
262 _cleanup_bus_message_unref_ sd_bus_message *request = NULL;
263 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
264 int authorized = false, challenge = false;
265 const char *sender, **k, **v;
267 sender = sd_bus_message_get_sender(call);
271 r = sd_bus_message_new_method_call(
274 "org.freedesktop.PolicyKit1",
275 "/org/freedesktop/PolicyKit1/Authority",
276 "org.freedesktop.PolicyKit1.Authority",
277 "CheckAuthorization");
281 r = sd_bus_message_append(
284 "system-bus-name", 1, "name", "s", sender,
289 r = sd_bus_message_open_container(request, 'a', "{ss}");
293 STRV_FOREACH_PAIR(k, v, details) {
294 r = sd_bus_message_append(request, "{ss}", *k, *v);
299 r = sd_bus_message_close_container(request);
303 r = sd_bus_message_append(request, "us", 0, NULL);
307 r = sd_bus_call(call->bus, request, 0, e, &reply);
309 /* Treat no PK available as access denied */
310 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN)) {
311 sd_bus_error_free(e);
318 r = sd_bus_message_enter_container(reply, 'r', "bba{ss}");
322 r = sd_bus_message_read(reply, "bb", &authorized, &challenge);
330 *_challenge = challenge;
341 typedef struct AsyncPolkitQuery {
342 sd_bus_message *request, *reply;
343 sd_bus_message_handler_t callback;
349 static void async_polkit_query_free(AsyncPolkitQuery *q) {
354 sd_bus_slot_unref(q->slot);
356 if (q->registry && q->request)
357 hashmap_remove(q->registry, q->request);
359 sd_bus_message_unref(q->request);
360 sd_bus_message_unref(q->reply);
365 static int async_polkit_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) {
366 _cleanup_bus_error_free_ sd_bus_error error_buffer = SD_BUS_ERROR_NULL;
367 AsyncPolkitQuery *q = userdata;
373 q->slot = sd_bus_slot_unref(q->slot);
374 q->reply = sd_bus_message_ref(reply);
376 r = sd_bus_message_rewind(q->request, true);
378 r = sd_bus_reply_method_errno(q->request, r, NULL);
382 r = q->callback(q->request, q->userdata, &error_buffer);
383 r = bus_maybe_reply_error(q->request, r, &error_buffer);
386 async_polkit_query_free(q);
393 int bus_verify_polkit_async(
394 sd_bus_message *call,
397 const char **details,
401 sd_bus_error *error) {
404 _cleanup_bus_message_unref_ sd_bus_message *pk = NULL;
406 const char *sender, **k, **v;
407 sd_bus_message_handler_t callback;
417 r = check_good_user(call, good_user);
422 q = hashmap_get(*registry, call);
424 int authorized, challenge;
426 /* This is the second invocation of this function, and
427 * there's already a response from polkit, let's
431 if (sd_bus_message_is_method_error(q->reply, NULL)) {
432 const sd_bus_error *e;
434 /* Copy error from polkit reply */
435 e = sd_bus_message_get_error(q->reply);
436 sd_bus_error_copy(error, e);
438 /* Treat no PK available as access denied */
439 if (sd_bus_error_has_name(e, SD_BUS_ERROR_SERVICE_UNKNOWN))
442 return -sd_bus_error_get_errno(e);
445 r = sd_bus_message_enter_container(q->reply, 'r', "bba{ss}");
447 r = sd_bus_message_read(q->reply, "bb", &authorized, &challenge);
456 return sd_bus_error_set(error, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED, "Interactive authentication required.");
462 r = sd_bus_query_sender_privilege(call, capability);
469 if (sd_bus_get_current_message(call->bus) != call)
472 callback = sd_bus_get_current_handler(call->bus);
476 userdata = sd_bus_get_current_userdata(call->bus);
478 sender = sd_bus_message_get_sender(call);
482 c = sd_bus_message_get_allow_interactive_authorization(call);
488 r = hashmap_ensure_allocated(registry, NULL);
492 r = sd_bus_message_new_method_call(
495 "org.freedesktop.PolicyKit1",
496 "/org/freedesktop/PolicyKit1/Authority",
497 "org.freedesktop.PolicyKit1.Authority",
498 "CheckAuthorization");
502 r = sd_bus_message_append(
505 "system-bus-name", 1, "name", "s", sender,
510 r = sd_bus_message_open_container(pk, 'a', "{ss}");
514 STRV_FOREACH_PAIR(k, v, details) {
515 r = sd_bus_message_append(pk, "{ss}", *k, *v);
520 r = sd_bus_message_close_container(pk);
524 r = sd_bus_message_append(pk, "us", !!interactive, NULL);
528 q = new0(AsyncPolkitQuery, 1);
532 q->request = sd_bus_message_ref(call);
533 q->callback = callback;
534 q->userdata = userdata;
536 r = hashmap_put(*registry, call, q);
538 async_polkit_query_free(q);
542 q->registry = *registry;
544 r = sd_bus_call_async(call->bus, &q->slot, pk, async_polkit_callback, q, 0);
546 async_polkit_query_free(q);
556 void bus_verify_polkit_async_registry_free(Hashmap *registry) {
560 while ((q = hashmap_steal_first(registry)))
561 async_polkit_query_free(q);
563 hashmap_free(registry);
567 #if 0 /// UNNEEDED by elogind
568 int bus_check_peercred(sd_bus *c) {
575 fd = sd_bus_get_fd(c);
579 l = sizeof(struct ucred);
580 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
583 if (l != sizeof(struct ucred))
586 if (ucred.uid != 0 && ucred.uid != geteuid())
592 int bus_connect_system_systemd(sd_bus **_bus) {
593 _cleanup_bus_unref_ sd_bus *bus = NULL;
599 return sd_bus_default_system(_bus);
601 /* If we are root and kdbus is not available, then let's talk
602 * directly to the system instance, instead of going via the
605 r = sd_bus_new(&bus);
609 r = sd_bus_set_address(bus, KERNEL_SYSTEM_BUS_ADDRESS);
613 bus->bus_client = true;
615 r = sd_bus_start(bus);
622 bus = sd_bus_unref(bus);
624 r = sd_bus_new(&bus);
628 r = sd_bus_set_address(bus, "unix:path=/run/systemd/private");
632 r = sd_bus_start(bus);
634 return sd_bus_default_system(_bus);
636 r = bus_check_peercred(bus);
646 int bus_connect_user_systemd(sd_bus **_bus) {
647 _cleanup_bus_unref_ sd_bus *bus = NULL;
648 _cleanup_free_ char *ee = NULL;
652 /* Try via kdbus first, and then directly */
656 r = sd_bus_new(&bus);
660 if (asprintf(&bus->address, KERNEL_USER_BUS_ADDRESS_FMT, getuid()) < 0)
663 bus->bus_client = true;
665 r = sd_bus_start(bus);
672 bus = sd_bus_unref(bus);
674 e = secure_getenv("XDG_RUNTIME_DIR");
676 return sd_bus_default_user(_bus);
678 ee = bus_address_escape(e);
682 r = sd_bus_new(&bus);
686 bus->address = strjoin("unix:path=", ee, "/systemd/private", NULL);
690 r = sd_bus_start(bus);
692 return sd_bus_default_user(_bus);
694 r = bus_check_peercred(bus);
705 int bus_print_property(const char *name, sd_bus_message *property, bool all) {
707 const char *contents;
713 r = sd_bus_message_peek_type(property, &type, &contents);
719 case SD_BUS_TYPE_STRING: {
722 r = sd_bus_message_read_basic(property, type, &s);
726 if (all || !isempty(s)) {
727 _cleanup_free_ char *escaped = NULL;
729 escaped = xescape(s, "\n");
733 printf("%s=%s\n", name, escaped);
739 case SD_BUS_TYPE_BOOLEAN: {
742 r = sd_bus_message_read_basic(property, type, &b);
746 printf("%s=%s\n", name, yes_no(b));
751 case SD_BUS_TYPE_UINT64: {
754 r = sd_bus_message_read_basic(property, type, &u);
758 /* Yes, heuristics! But we can change this check
759 * should it turn out to not be sufficient */
761 if (endswith(name, "Timestamp")) {
762 char timestamp[FORMAT_TIMESTAMP_MAX], *t;
764 t = format_timestamp(timestamp, sizeof(timestamp), u);
766 printf("%s=%s\n", name, strempty(t));
768 } else if (strstr(name, "USec")) {
769 char timespan[FORMAT_TIMESPAN_MAX];
771 printf("%s=%s\n", name, format_timespan(timespan, sizeof(timespan), u, 0));
773 printf("%s=%llu\n", name, (unsigned long long) u);
778 case SD_BUS_TYPE_INT64: {
781 r = sd_bus_message_read_basic(property, type, &i);
785 printf("%s=%lld\n", name, (long long) i);
790 case SD_BUS_TYPE_UINT32: {
793 r = sd_bus_message_read_basic(property, type, &u);
797 if (strstr(name, "UMask") || strstr(name, "Mode"))
798 printf("%s=%04o\n", name, u);
800 printf("%s=%u\n", name, (unsigned) u);
805 case SD_BUS_TYPE_INT32: {
808 r = sd_bus_message_read_basic(property, type, &i);
812 printf("%s=%i\n", name, (int) i);
816 case SD_BUS_TYPE_DOUBLE: {
819 r = sd_bus_message_read_basic(property, type, &d);
823 printf("%s=%g\n", name, d);
827 case SD_BUS_TYPE_ARRAY:
828 if (streq(contents, "s")) {
832 r = sd_bus_message_enter_container(property, SD_BUS_TYPE_ARRAY, contents);
836 while((r = sd_bus_message_read_basic(property, SD_BUS_TYPE_STRING, &str)) > 0) {
837 _cleanup_free_ char *escaped = NULL;
842 escaped = xescape(str, "\n ");
846 printf("%s%s", first ? "" : " ", escaped);
858 r = sd_bus_message_exit_container(property);
864 } else if (streq(contents, "y")) {
868 r = sd_bus_message_read_array(property, SD_BUS_TYPE_BYTE, (const void**) &u, &n);
877 for (i = 0; i < n; i++)
878 printf("%02x", u[i]);
885 } else if (streq(contents, "u")) {
889 r = sd_bus_message_read_array(property, SD_BUS_TYPE_UINT32, (const void**) &u, &n);
898 for (i = 0; i < n; i++)
899 printf("%08x", u[i]);
913 int bus_print_all_properties(sd_bus *bus, const char *dest, const char *path, char **filter, bool all) {
914 _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
915 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
921 r = sd_bus_call_method(bus,
924 "org.freedesktop.DBus.Properties",
932 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "{sv}");
936 while ((r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
938 const char *contents;
940 r = sd_bus_message_read_basic(reply, SD_BUS_TYPE_STRING, &name);
944 if (!filter || strv_find(filter, name)) {
945 r = sd_bus_message_peek_type(reply, NULL, &contents);
949 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_VARIANT, contents);
953 r = bus_print_property(name, reply, all);
958 printf("%s=[unprintable]\n", name);
959 /* skip what we didn't read */
960 r = sd_bus_message_skip(reply, contents);
965 r = sd_bus_message_exit_container(reply);
969 r = sd_bus_message_skip(reply, "v");
974 r = sd_bus_message_exit_container(reply);
981 r = sd_bus_message_exit_container(reply);
988 int bus_map_id128(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
989 sd_id128_t *p = userdata;
994 r = sd_bus_message_read_array(m, SD_BUS_TYPE_BYTE, &v, &n);
1001 memcpy((*p).bytes, v, n);
1008 static int map_basic(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1012 r = sd_bus_message_peek_type(m, &type, NULL);
1017 case SD_BUS_TYPE_STRING: {
1019 char **p = userdata;
1021 r = sd_bus_message_read_basic(m, type, &s);
1028 r = free_and_strdup(p, s);
1032 case SD_BUS_TYPE_ARRAY: {
1033 _cleanup_strv_free_ char **l = NULL;
1034 char ***p = userdata;
1036 r = bus_message_read_strv_extend(m, &l);
1047 case SD_BUS_TYPE_BOOLEAN: {
1051 r = sd_bus_message_read_basic(m, type, &b);
1060 case SD_BUS_TYPE_UINT32: {
1062 uint32_t *p = userdata;
1064 r = sd_bus_message_read_basic(m, type, &u);
1073 case SD_BUS_TYPE_UINT64: {
1075 uint64_t *p = userdata;
1077 r = sd_bus_message_read_basic(m, type, &t);
1093 int bus_message_map_all_properties(
1095 const struct bus_properties_map *map,
1098 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1104 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "{sv}");
1108 while ((r = sd_bus_message_enter_container(m, SD_BUS_TYPE_DICT_ENTRY, "sv")) > 0) {
1109 const struct bus_properties_map *prop;
1111 const char *contents;
1115 r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member);
1119 for (i = 0, prop = NULL; map[i].member; i++)
1120 if (streq(map[i].member, member)) {
1126 r = sd_bus_message_peek_type(m, NULL, &contents);
1130 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_VARIANT, contents);
1134 v = (uint8_t *)userdata + prop->offset;
1136 r = prop->set(sd_bus_message_get_bus(m), member, m, &error, v);
1138 r = map_basic(sd_bus_message_get_bus(m), member, m, &error, v);
1142 r = sd_bus_message_exit_container(m);
1146 r = sd_bus_message_skip(m, "v");
1151 r = sd_bus_message_exit_container(m);
1158 return sd_bus_message_exit_container(m);
1161 #if 0 /// UNNEEDED by elogind
1162 int bus_message_map_properties_changed(
1164 const struct bus_properties_map *map,
1168 int r, invalidated, i;
1173 r = bus_message_map_all_properties(m, map, userdata);
1177 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "s");
1182 while ((r = sd_bus_message_read_basic(m, SD_BUS_TYPE_STRING, &member)) > 0)
1183 for (i = 0; map[i].member; i++)
1184 if (streq(map[i].member, member)) {
1191 r = sd_bus_message_exit_container(m);
1199 int bus_map_all_properties(
1201 const char *destination,
1203 const struct bus_properties_map *map,
1206 _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
1207 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1211 assert(destination);
1215 r = sd_bus_call_method(
1219 "org.freedesktop.DBus.Properties",
1227 return bus_message_map_all_properties(m, map, userdata);
1230 int bus_connect_transport(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1233 assert(transport >= 0);
1234 assert(transport < _BUS_TRANSPORT_MAX);
1237 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1238 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1240 switch (transport) {
1242 case BUS_TRANSPORT_LOCAL:
1243 #if 0 /// elogind does not support a user bus
1245 r = sd_bus_default_user(bus);
1248 r = sd_bus_default_system(bus);
1252 case BUS_TRANSPORT_REMOTE:
1253 r = sd_bus_open_system_remote(bus, host);
1256 case BUS_TRANSPORT_MACHINE:
1257 r = sd_bus_open_system_machine(bus, host);
1261 assert_not_reached("Hmm, unknown transport type.");
1267 #if 0 /// UNNEEDED by elogind
1268 int bus_connect_transport_systemd(BusTransport transport, const char *host, bool user, sd_bus **bus) {
1271 assert(transport >= 0);
1272 assert(transport < _BUS_TRANSPORT_MAX);
1275 assert_return((transport == BUS_TRANSPORT_LOCAL) == !host, -EINVAL);
1276 assert_return(transport == BUS_TRANSPORT_LOCAL || !user, -EOPNOTSUPP);
1278 switch (transport) {
1280 case BUS_TRANSPORT_LOCAL:
1282 r = bus_connect_user_systemd(bus);
1284 r = bus_connect_system_systemd(bus);
1288 case BUS_TRANSPORT_REMOTE:
1289 r = sd_bus_open_system_remote(bus, host);
1292 case BUS_TRANSPORT_MACHINE:
1293 r = sd_bus_open_system_machine(bus, host);
1297 assert_not_reached("Hmm, unknown transport type.");
1304 int bus_property_get_bool(
1307 const char *interface,
1308 const char *property,
1309 sd_bus_message *reply,
1311 sd_bus_error *error) {
1313 int b = *(bool*) userdata;
1315 return sd_bus_message_append_basic(reply, 'b', &b);
1318 #if __SIZEOF_SIZE_T__ != 8
1319 int bus_property_get_size(
1322 const char *interface,
1323 const char *property,
1324 sd_bus_message *reply,
1326 sd_bus_error *error) {
1328 uint64_t sz = *(size_t*) userdata;
1330 return sd_bus_message_append_basic(reply, 't', &sz);
1334 #if __SIZEOF_LONG__ != 8
1335 int bus_property_get_long(
1338 const char *interface,
1339 const char *property,
1340 sd_bus_message *reply,
1342 sd_bus_error *error) {
1344 int64_t l = *(long*) userdata;
1346 return sd_bus_message_append_basic(reply, 'x', &l);
1349 int bus_property_get_ulong(
1352 const char *interface,
1353 const char *property,
1354 sd_bus_message *reply,
1356 sd_bus_error *error) {
1358 uint64_t ul = *(unsigned long*) userdata;
1360 return sd_bus_message_append_basic(reply, 't', &ul);
1364 int bus_log_parse_error(int r) {
1365 return log_error_errno(r, "Failed to parse bus message: %m");
1368 #if 0 /// UNNEEDED by elogind
1369 int bus_log_create_error(int r) {
1370 return log_error_errno(r, "Failed to create bus message: %m");
1373 int bus_parse_unit_info(sd_bus_message *message, UnitInfo *u) {
1379 return sd_bus_message_read(
1394 int bus_append_unit_property_assignment(sd_bus_message *m, const char *assignment) {
1395 const char *eq, *field;
1401 eq = strchr(assignment, '=');
1403 log_error("Not an assignment: %s", assignment);
1407 field = strndupa(assignment, eq - assignment);
1410 if (streq(field, "CPUQuota")) {
1414 r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, "CPUQuotaPerSecUSec");
1416 return bus_log_create_error(r);
1418 r = sd_bus_message_append(m, "v", "t", USEC_INFINITY);
1420 } else if (endswith(eq, "%")) {
1423 if (sscanf(eq, "%lf%%", &percent) != 1 || percent <= 0) {
1424 log_error("CPU quota '%s' invalid.", eq);
1428 r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, "CPUQuotaPerSecUSec");
1430 return bus_log_create_error(r);
1432 r = sd_bus_message_append(m, "v", "t", (usec_t) percent * USEC_PER_SEC / 100);
1434 log_error("CPU quota needs to be in percent.");
1439 return bus_log_create_error(r);
1443 } else if (streq(field, "EnvironmentFile")) {
1445 r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, "EnvironmentFiles");
1447 return bus_log_create_error(r);
1449 r = sd_bus_message_append(m, "v", "a(sb)", 1,
1450 eq[0] == '-' ? eq + 1 : eq,
1453 return bus_log_create_error(r);
1457 } else if (streq(field, "RandomizedDelaySec")) {
1460 r = parse_sec(eq, &t);
1462 return log_error_errno(r, "Failed to parse RandomizedDelaySec= parameter: %s", eq);
1464 r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, "RandomizedDelayUSec");
1466 return bus_log_create_error(r);
1468 r = sd_bus_message_append(m, "v", "t", t);
1470 return bus_log_create_error(r);
1475 r = sd_bus_message_append_basic(m, SD_BUS_TYPE_STRING, field);
1477 return bus_log_create_error(r);
1479 if (STR_IN_SET(field,
1480 "CPUAccounting", "MemoryAccounting", "BlockIOAccounting", "TasksAccounting",
1481 "SendSIGHUP", "SendSIGKILL", "WakeSystem", "DefaultDependencies",
1482 "IgnoreSIGPIPE", "TTYVHangup", "TTYReset", "RemainAfterExit",
1483 "PrivateTmp", "PrivateDevices", "PrivateNetwork", "NoNewPrivileges",
1484 "SyslogLevelPrefix", "Delegate", "RemainAfterElapse")) {
1486 r = parse_boolean(eq);
1488 return log_error_errno(r, "Failed to parse boolean assignment %s.", assignment);
1490 r = sd_bus_message_append(m, "v", "b", r);
1492 } else if (streq(field, "MemoryLimit")) {
1495 if (isempty(eq) || streq(eq, "infinity"))
1496 bytes = (uint64_t) -1;
1498 r = parse_size(eq, 1024, &bytes);
1500 log_error("Failed to parse bytes specification %s", assignment);
1505 r = sd_bus_message_append(m, "v", "t", bytes);
1507 } else if (streq(field, "TasksMax")) {
1510 if (isempty(eq) || streq(eq, "infinity"))
1513 r = safe_atou64(eq, &n);
1515 log_error("Failed to parse maximum tasks specification %s", assignment);
1520 r = sd_bus_message_append(m, "v", "t", n);
1522 } else if (STR_IN_SET(field, "CPUShares", "StartupCPUShares")) {
1525 r = cg_cpu_shares_parse(eq, &u);
1527 log_error("Failed to parse %s value %s.", field, eq);
1531 r = sd_bus_message_append(m, "v", "t", u);
1533 } else if (STR_IN_SET(field, "BlockIOWeight", "StartupBlockIOWeight")) {
1536 r = cg_cpu_shares_parse(eq, &u);
1538 log_error("Failed to parse %s value %s.", field, eq);
1542 r = sd_bus_message_append(m, "v", "t", u);
1544 } else if (STR_IN_SET(field,
1545 "User", "Group", "DevicePolicy", "KillMode",
1546 "UtmpIdentifier", "UtmpMode", "PAMName", "TTYPath",
1547 "StandardInput", "StandardOutput", "StandardError",
1548 "Description", "Slice", "Type", "WorkingDirectory",
1549 "RootDirectory", "SyslogIdentifier", "ProtectSystem",
1551 r = sd_bus_message_append(m, "v", "s", eq);
1553 else if (streq(field, "SyslogLevel")) {
1556 level = log_level_from_string(eq);
1558 log_error("Failed to parse %s value %s.", field, eq);
1562 r = sd_bus_message_append(m, "v", "i", level);
1564 } else if (streq(field, "SyslogFacility")) {
1567 facility = log_facility_unshifted_from_string(eq);
1569 log_error("Failed to parse %s value %s.", field, eq);
1573 r = sd_bus_message_append(m, "v", "i", facility);
1575 } else if (streq(field, "DeviceAllow")) {
1578 r = sd_bus_message_append(m, "v", "a(ss)", 0);
1580 const char *path, *rwm, *e;
1582 e = strchr(eq, ' ');
1584 path = strndupa(eq, e - eq);
1591 if (!path_startswith(path, "/dev")) {
1592 log_error("%s is not a device file in /dev.", path);
1596 r = sd_bus_message_append(m, "v", "a(ss)", 1, path, rwm);
1599 } else if (STR_IN_SET(field, "BlockIOReadBandwidth", "BlockIOWriteBandwidth")) {
1602 r = sd_bus_message_append(m, "v", "a(st)", 0);
1604 const char *path, *bandwidth, *e;
1607 e = strchr(eq, ' ');
1609 path = strndupa(eq, e - eq);
1612 log_error("Failed to parse %s value %s.", field, eq);
1616 if (!path_startswith(path, "/dev")) {
1617 log_error("%s is not a device file in /dev.", path);
1621 r = parse_size(bandwidth, 1000, &bytes);
1623 log_error("Failed to parse byte value %s.", bandwidth);
1627 r = sd_bus_message_append(m, "v", "a(st)", 1, path, bytes);
1630 } else if (streq(field, "BlockIODeviceWeight")) {
1633 r = sd_bus_message_append(m, "v", "a(st)", 0);
1635 const char *path, *weight, *e;
1638 e = strchr(eq, ' ');
1640 path = strndupa(eq, e - eq);
1643 log_error("Failed to parse %s value %s.", field, eq);
1647 if (!path_startswith(path, "/dev")) {
1648 log_error("%s is not a device file in /dev.", path);
1652 r = safe_atou64(weight, &u);
1654 log_error("Failed to parse %s value %s.", field, weight);
1657 r = sd_bus_message_append(m, "v", "a(st)", path, u);
1660 } else if (rlimit_from_string(field) >= 0) {
1663 if (streq(eq, "infinity"))
1666 r = safe_atou64(eq, &rl);
1668 log_error("Invalid resource limit: %s", eq);
1673 r = sd_bus_message_append(m, "v", "t", rl);
1675 } else if (streq(field, "Nice")) {
1678 r = safe_atoi32(eq, &i);
1680 log_error("Failed to parse %s value %s.", field, eq);
1684 r = sd_bus_message_append(m, "v", "i", i);
1686 } else if (STR_IN_SET(field, "Environment", "PassEnvironment")) {
1689 r = sd_bus_message_open_container(m, 'v', "as");
1691 return bus_log_create_error(r);
1693 r = sd_bus_message_open_container(m, 'a', "s");
1695 return bus_log_create_error(r);
1700 _cleanup_free_ char *word = NULL;
1702 r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES|EXTRACT_CUNESCAPE);
1704 log_error("Failed to parse Environment value %s", eq);
1710 if (streq(field, "Environment")) {
1711 if (!env_assignment_is_valid(word)) {
1712 log_error("Invalid environment assignment: %s", word);
1715 } else { /* PassEnvironment */
1716 if (!env_name_is_valid(word)) {
1717 log_error("Invalid environment variable name: %s", word);
1722 r = sd_bus_message_append_basic(m, 's', word);
1724 return bus_log_create_error(r);
1727 r = sd_bus_message_close_container(m);
1729 return bus_log_create_error(r);
1731 r = sd_bus_message_close_container(m);
1733 } else if (streq(field, "KillSignal")) {
1736 sig = signal_from_string_try_harder(eq);
1738 log_error("Failed to parse %s value %s.", field, eq);
1742 r = sd_bus_message_append(m, "v", "i", sig);
1744 } else if (streq(field, "AccuracySec")) {
1747 r = parse_sec(eq, &u);
1749 log_error("Failed to parse %s value %s", field, eq);
1753 r = sd_bus_message_append(m, "v", "t", u);
1754 } else if (streq(field, "TimerSlackNSec")) {
1757 r = parse_nsec(eq, &n);
1759 log_error("Failed to parse %s value %s", field, eq);
1763 r = sd_bus_message_append(m, "v", "t", n);
1764 } else if (streq(field, "OOMScoreAdjust")) {
1767 r = safe_atoi(eq, &oa);
1769 log_error("Failed to parse %s value %s", field, eq);
1773 if (!oom_score_adjust_is_valid(oa)) {
1774 log_error("OOM score adjust value out of range");
1778 r = sd_bus_message_append(m, "v", "i", oa);
1779 } else if (STR_IN_SET(field, "ReadWriteDirectories", "ReadOnlyDirectories", "InaccessibleDirectories")) {
1782 r = sd_bus_message_open_container(m, 'v', "as");
1784 return bus_log_create_error(r);
1786 r = sd_bus_message_open_container(m, 'a', "s");
1788 return bus_log_create_error(r);
1793 _cleanup_free_ char *word = NULL;
1796 r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES);
1798 log_error("Failed to parse %s value %s", field, eq);
1804 if (!utf8_is_valid(word)) {
1805 log_error("Failed to parse %s value %s", field, eq);
1809 offset = word[0] == '-';
1810 if (!path_is_absolute(word + offset)) {
1811 log_error("Failed to parse %s value %s", field, eq);
1815 path_kill_slashes(word + offset);
1817 r = sd_bus_message_append_basic(m, 's', word);
1819 return bus_log_create_error(r);
1822 r = sd_bus_message_close_container(m);
1824 return bus_log_create_error(r);
1826 r = sd_bus_message_close_container(m);
1828 } else if (streq(field, "RuntimeDirectory")) {
1831 r = sd_bus_message_open_container(m, 'v', "as");
1833 return bus_log_create_error(r);
1835 r = sd_bus_message_open_container(m, 'a', "s");
1837 return bus_log_create_error(r);
1842 _cleanup_free_ char *word = NULL;
1844 r = extract_first_word(&p, &word, NULL, EXTRACT_QUOTES);
1846 return log_error_errno(r, "Failed to parse %s value %s", field, eq);
1851 r = sd_bus_message_append_basic(m, 's', word);
1853 return bus_log_create_error(r);
1856 r = sd_bus_message_close_container(m);
1858 return bus_log_create_error(r);
1860 r = sd_bus_message_close_container(m);
1863 log_error("Unknown assignment %s.", assignment);
1868 return bus_log_create_error(r);
1874 typedef struct BusWaitForJobs {
1881 sd_bus_slot *slot_job_removed;
1882 sd_bus_slot *slot_disconnected;
1885 #if 0 /// UNNEEDED by elogind
1886 static int match_disconnected(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1889 log_error("Warning! D-Bus connection terminated.");
1890 sd_bus_close(sd_bus_message_get_bus(m));
1895 static int match_job_removed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1896 const char *path, *unit, *result;
1897 BusWaitForJobs *d = userdata;
1905 r = sd_bus_message_read(m, "uoss", &id, &path, &unit, &result);
1907 bus_log_parse_error(r);
1911 found = set_remove(d->jobs, (char*) path);
1917 if (!isempty(result))
1918 d->result = strdup(result);
1921 d->name = strdup(unit);
1926 void bus_wait_for_jobs_free(BusWaitForJobs *d) {
1930 set_free_free(d->jobs);
1932 sd_bus_slot_unref(d->slot_disconnected);
1933 sd_bus_slot_unref(d->slot_job_removed);
1935 sd_bus_unref(d->bus);
1943 int bus_wait_for_jobs_new(sd_bus *bus, BusWaitForJobs **ret) {
1944 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *d = NULL;
1950 d = new0(BusWaitForJobs, 1);
1954 d->bus = sd_bus_ref(bus);
1956 /* When we are a bus client we match by sender. Direct
1957 * connections OTOH have no initialized sender field, and
1958 * hence we ignore the sender then */
1959 r = sd_bus_add_match(
1961 &d->slot_job_removed,
1964 "sender='org.freedesktop.systemd1',"
1965 "interface='org.freedesktop.systemd1.Manager',"
1966 "member='JobRemoved',"
1967 "path='/org/freedesktop/systemd1'" :
1969 "interface='org.freedesktop.systemd1.Manager',"
1970 "member='JobRemoved',"
1971 "path='/org/freedesktop/systemd1'",
1972 match_job_removed, d);
1976 r = sd_bus_add_match(
1978 &d->slot_disconnected,
1980 "sender='org.freedesktop.DBus.Local',"
1981 "interface='org.freedesktop.DBus.Local',"
1982 "member='Disconnected'",
1983 match_disconnected, d);
1993 static int bus_process_wait(sd_bus *bus) {
1997 r = sd_bus_process(bus, NULL);
2003 r = sd_bus_wait(bus, (uint64_t) -1);
2009 static int bus_job_get_service_result(BusWaitForJobs *d, char **result) {
2010 _cleanup_free_ char *dbus_path = NULL;
2016 dbus_path = unit_dbus_path_from_name(d->name);
2020 return sd_bus_get_property_string(d->bus,
2021 "org.freedesktop.systemd1",
2023 "org.freedesktop.systemd1.Service",
2029 static const struct {
2030 const char *result, *explanation;
2031 } explanations [] = {
2032 { "resources", "a configured resource limit was exceeded" },
2033 { "timeout", "a timeout was exceeded" },
2034 { "exit-code", "the control process exited with error code" },
2035 { "signal", "a fatal signal was delivered to the control process" },
2036 { "core-dump", "a fatal signal was delivered causing the control process to dump core" },
2037 { "watchdog", "the service failed to send watchdog ping" },
2038 { "start-limit", "start of the service was attempted too often" }
2041 static void log_job_error_with_service_result(const char* service, const char *result) {
2042 _cleanup_free_ char *service_shell_quoted = NULL;
2046 service_shell_quoted = shell_maybe_quote(service);
2048 if (!isempty(result)) {
2051 for (i = 0; i < ELEMENTSOF(explanations); ++i)
2052 if (streq(result, explanations[i].result))
2055 if (i < ELEMENTSOF(explanations)) {
2056 log_error("Job for %s failed because %s. See \"systemctl status %s\" and \"journalctl -xe\" for details.\n",
2058 explanations[i].explanation,
2059 strna(service_shell_quoted));
2065 log_error("Job for %s failed. See \"systemctl status %s\" and \"journalctl -xe\" for details.\n",
2067 strna(service_shell_quoted));
2070 /* For some results maybe additional explanation is required */
2071 if (streq_ptr(result, "start-limit"))
2072 log_info("To force a start use \"systemctl reset-failed %1$s\" followed by \"systemctl start %1$s\" again.",
2073 strna(service_shell_quoted));
2076 static int check_wait_response(BusWaitForJobs *d, bool quiet) {
2082 if (streq(d->result, "canceled"))
2083 log_error("Job for %s canceled.", strna(d->name));
2084 else if (streq(d->result, "timeout"))
2085 log_error("Job for %s timed out.", strna(d->name));
2086 else if (streq(d->result, "dependency"))
2087 log_error("A dependency job for %s failed. See 'journalctl -xe' for details.", strna(d->name));
2088 else if (streq(d->result, "invalid"))
2089 log_error("Job for %s invalid.", strna(d->name));
2090 else if (streq(d->result, "assert"))
2091 log_error("Assertion failed on job for %s.", strna(d->name));
2092 else if (streq(d->result, "unsupported"))
2093 log_error("Operation on or unit type of %s not supported on this system.", strna(d->name));
2094 else if (!streq(d->result, "done") && !streq(d->result, "skipped")) {
2097 _cleanup_free_ char *result = NULL;
2099 q = bus_job_get_service_result(d, &result);
2101 log_debug_errno(q, "Failed to get Result property of service %s: %m", d->name);
2103 log_job_error_with_service_result(d->name, result);
2105 log_error("Job failed. See \"journalctl -xe\" for details.");
2109 if (streq(d->result, "canceled"))
2111 else if (streq(d->result, "timeout"))
2113 else if (streq(d->result, "dependency"))
2115 else if (streq(d->result, "invalid"))
2117 else if (streq(d->result, "assert"))
2119 else if (streq(d->result, "unsupported"))
2121 else if (!streq(d->result, "done") && !streq(d->result, "skipped"))
2127 int bus_wait_for_jobs(BusWaitForJobs *d, bool quiet) {
2132 while (!set_isempty(d->jobs)) {
2135 q = bus_process_wait(d->bus);
2137 return log_error_errno(q, "Failed to wait for response: %m");
2140 q = check_wait_response(d, quiet);
2141 /* Return the first error as it is most likely to be
2143 if (q < 0 && r == 0)
2146 log_debug_errno(q, "Got result %s/%m for job %s", strna(d->result), strna(d->name));
2149 d->name = mfree(d->name);
2150 d->result = mfree(d->result);
2156 int bus_wait_for_jobs_add(BusWaitForJobs *d, const char *path) {
2161 r = set_ensure_allocated(&d->jobs, &string_hash_ops);
2165 return set_put_strdup(d->jobs, path);
2168 int bus_wait_for_jobs_one(BusWaitForJobs *d, const char *path, bool quiet) {
2171 r = bus_wait_for_jobs_add(d, path);
2175 return bus_wait_for_jobs(d, quiet);
2178 int bus_deserialize_and_dump_unit_file_changes(sd_bus_message *m, bool quiet, UnitFileChange **changes, unsigned *n_changes) {
2179 const char *type, *path, *source;
2182 r = sd_bus_message_enter_container(m, SD_BUS_TYPE_ARRAY, "(sss)");
2184 return bus_log_parse_error(r);
2186 while ((r = sd_bus_message_read(m, "(sss)", &type, &path, &source)) > 0) {
2188 if (streq(type, "symlink"))
2189 log_info("Created symlink from %s to %s.", path, source);
2191 log_info("Removed symlink %s.", path);
2194 r = unit_file_changes_add(changes, n_changes, streq(type, "symlink") ? UNIT_FILE_SYMLINK : UNIT_FILE_UNLINK, path, source);
2199 return bus_log_parse_error(r);
2201 r = sd_bus_message_exit_container(m);
2203 return bus_log_parse_error(r);
2209 * bus_path_encode_unique() - encode unique object path
2210 * @b: bus connection or NULL
2211 * @prefix: object path prefix
2212 * @sender_id: unique-name of client, or NULL
2213 * @external_id: external ID to be chosen by client, or NULL
2214 * @ret_path: storage for encoded object path pointer
2216 * Whenever we provide a bus API that allows clients to create and manage
2217 * server-side objects, we need to provide a unique name for these objects. If
2218 * we let the server choose the name, we suffer from a race condition: If a
2219 * client creates an object asynchronously, it cannot destroy that object until
2220 * it received the method reply. It cannot know the name of the new object,
2221 * thus, it cannot destroy it. Furthermore, it enforces a round-trip.
2223 * Therefore, many APIs allow the client to choose the unique name for newly
2224 * created objects. There're two problems to solve, though:
2225 * 1) Object names are usually defined via dbus object paths, which are
2226 * usually globally namespaced. Therefore, multiple clients must be able
2227 * to choose unique object names without interference.
2228 * 2) If multiple libraries share the same bus connection, they must be
2229 * able to choose unique object names without interference.
2230 * The first problem is solved easily by prefixing a name with the
2231 * unique-bus-name of a connection. The server side must enforce this and
2232 * reject any other name. The second problem is solved by providing unique
2233 * suffixes from within sd-bus.
2235 * This helper allows clients to create unique object-paths. It uses the
2236 * template '/prefix/sender_id/external_id' and returns the new path in
2237 * @ret_path (must be freed by the caller).
2238 * If @sender_id is NULL, the unique-name of @b is used. If @external_id is
2239 * NULL, this function allocates a unique suffix via @b (by requesting a new
2240 * cookie). If both @sender_id and @external_id are given, @b can be passed as
2243 * Returns: 0 on success, negative error code on failure.
2245 int bus_path_encode_unique(sd_bus *b, const char *prefix, const char *sender_id, const char *external_id, char **ret_path) {
2246 _cleanup_free_ char *sender_label = NULL, *external_label = NULL;
2247 char external_buf[DECIMAL_STR_MAX(uint64_t)], *p;
2250 assert_return(b || (sender_id && external_id), -EINVAL);
2251 assert_return(object_path_is_valid(prefix), -EINVAL);
2252 assert_return(ret_path, -EINVAL);
2255 r = sd_bus_get_unique_name(b, &sender_id);
2261 xsprintf(external_buf, "%"PRIu64, ++b->cookie);
2262 external_id = external_buf;
2265 sender_label = bus_label_escape(sender_id);
2269 external_label = bus_label_escape(external_id);
2270 if (!external_label)
2273 p = strjoin(prefix, "/", sender_label, "/", external_label, NULL);
2282 * bus_path_decode_unique() - decode unique object path
2283 * @path: object path to decode
2284 * @prefix: object path prefix
2285 * @ret_sender: output parameter for sender-id label
2286 * @ret_external: output parameter for external-id label
2288 * This does the reverse of bus_path_encode_unique() (see its description for
2289 * details). Both trailing labels, sender-id and external-id, are unescaped and
2290 * returned in the given output parameters (the caller must free them).
2292 * Note that this function returns 0 if the path does not match the template
2293 * (see bus_path_encode_unique()), 1 if it matched.
2295 * Returns: Negative error code on failure, 0 if the given object path does not
2296 * match the template (return parameters are set to NULL), 1 if it was
2297 * parsed successfully (return parameters contain allocated labels).
2299 int bus_path_decode_unique(const char *path, const char *prefix, char **ret_sender, char **ret_external) {
2301 char *sender, *external;
2303 assert(object_path_is_valid(path));
2304 assert(object_path_is_valid(prefix));
2306 assert(ret_external);
2308 p = object_path_startswith(path, prefix);
2311 *ret_external = NULL;
2318 *ret_external = NULL;
2322 sender = bus_label_unescape_n(p, q - p);
2323 external = bus_label_unescape(q + 1);
2324 if (!sender || !external) {
2330 *ret_sender = sender;
2331 *ret_external = external;
2336 bool is_kdbus_wanted(void) {
2337 _cleanup_free_ char *value = NULL;
2339 const bool configured = true;
2341 const bool configured = false;
2346 if (get_proc_cmdline_key("kdbus", NULL) > 0)
2349 r = get_proc_cmdline_key("kdbus=", &value);
2353 return parse_boolean(value) == 1;
2356 bool is_kdbus_available(void) {
2357 _cleanup_close_ int fd = -1;
2358 struct kdbus_cmd cmd = { .size = sizeof(cmd), .flags = KDBUS_FLAG_NEGOTIATE };
2360 if (!is_kdbus_wanted())
2363 fd = open("/sys/fs/kdbus/control", O_RDWR | O_CLOEXEC | O_NONBLOCK | O_NOCTTY);
2367 return ioctl(fd, KDBUS_CMD_BUS_MAKE, &cmd) >= 0;
2370 #if 0 /// UNNEEDED by elogind
2371 int bus_property_get_rlimit(
2374 const char *interface,
2375 const char *property,
2376 sd_bus_message *reply,
2378 sd_bus_error *error) {
2383 const char *is_soft;
2389 is_soft = endswith(property, "Soft");
2390 rl = *(struct rlimit**) userdata;
2392 x = is_soft ? rl->rlim_cur : rl->rlim_max;
2394 struct rlimit buf = {};
2398 s = is_soft ? strndupa(property, is_soft - property) : property;
2400 z = rlimit_from_string(strstr(s, "Limit"));
2404 x = is_soft ? buf.rlim_cur : buf.rlim_max;
2407 /* rlim_t might have different sizes, let's map
2408 * RLIMIT_INFINITY to (uint64_t) -1, so that it is the same on
2410 u = x == RLIM_INFINITY ? (uint64_t) -1 : (uint64_t) x;
2412 return sd_bus_message_append(reply, "t", u);