1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <linux/loop.h>
5 #include "bus-common-errors.h"
7 #include "chase-symlinks.h"
8 #include "conf-files.h"
10 #include "data-fd-util.h"
12 #include "dirent-util.h"
13 #include "discover-image.h"
14 #include "dissect-image.h"
17 #include "errno-list.h"
19 #include "extension-release.h"
25 #include "locale-util.h"
26 #include "loop-util.h"
28 #include "nulstr-util.h"
30 #include "path-lookup.h"
32 #include "process-util.h"
33 #include "selinux-util.h"
35 #include "signal-util.h"
36 #include "socket-util.h"
37 #include "sort-util.h"
38 #include "string-table.h"
40 #include "tmpfile-util.h"
41 #include "user-util.h"
43 /* Markers used in the first line of our 20-portable.conf unit file drop-in to determine, that a) the unit file was
44 * dropped there by the portable service logic and b) for which image it was dropped there. */
45 #define PORTABLE_DROPIN_MARKER_BEGIN "# Drop-in created for image '"
46 #define PORTABLE_DROPIN_MARKER_END "', do not edit."
48 static bool prefix_match(const char *unit
, const char *prefix
) {
51 p
= startswith(unit
, prefix
);
55 /* Only respect prefixes followed by dash or dot or when there's a complete match */
56 return IN_SET(*p
, '-', '.', '@', 0);
59 static bool unit_match(const char *unit
, char **matches
) {
62 dot
= strrchr(unit
, '.');
66 if (!STR_IN_SET(dot
, ".service", ".socket", ".target", ".timer", ".path"))
69 /* Empty match expression means: everything */
70 if (strv_isempty(matches
))
73 /* Otherwise, at least one needs to match */
74 STRV_FOREACH(i
, matches
)
75 if (prefix_match(unit
, *i
))
81 static PortableMetadata
*portable_metadata_new(const char *name
, const char *path
, const char *selinux_label
, int fd
) {
84 m
= malloc0(offsetof(PortableMetadata
, name
) + strlen(name
) + 1);
88 /* In case of a layered attach, we want to remember which image the unit came from */
90 m
->image_path
= strdup(path
);
95 /* The metadata file might have SELinux labels, we need to carry them and reapply them */
96 if (!isempty(selinux_label
)) {
97 m
->selinux_label
= strdup(selinux_label
);
98 if (!m
->selinux_label
) {
104 strcpy(m
->name
, name
);
110 PortableMetadata
*portable_metadata_unref(PortableMetadata
*i
) {
117 free(i
->selinux_label
);
122 static int compare_metadata(PortableMetadata
*const *x
, PortableMetadata
*const *y
) {
123 return strcmp((*x
)->name
, (*y
)->name
);
126 int portable_metadata_hashmap_to_sorted_array(Hashmap
*unit_files
, PortableMetadata
***ret
) {
128 _cleanup_free_ PortableMetadata
**sorted
= NULL
;
129 PortableMetadata
*item
;
132 sorted
= new(PortableMetadata
*, hashmap_size(unit_files
));
136 HASHMAP_FOREACH(item
, unit_files
)
139 assert(k
== hashmap_size(unit_files
));
141 typesafe_qsort(sorted
, k
, compare_metadata
);
143 *ret
= TAKE_PTR(sorted
);
147 static int send_one_fd_iov_with_data_fd(
149 const struct iovec
*iov
,
153 _cleanup_close_
int data_fd
= -1;
155 assert(iov
|| iovlen
== 0);
156 assert(socket_fd
>= 0);
159 data_fd
= copy_data_fd(fd
);
163 return send_one_fd_iov(socket_fd
, data_fd
, iov
, iovlen
, 0);
166 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(portable_metadata_hash_ops
, char, string_hash_func
, string_compare_func
,
167 PortableMetadata
, portable_metadata_unref
);
169 static int extract_now(
172 const char *image_name
,
173 bool path_is_extension
,
175 PortableMetadata
**ret_os_release
,
176 Hashmap
**ret_unit_files
) {
178 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
179 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
180 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
181 _cleanup_close_
int os_release_fd
= -1;
182 _cleanup_free_
char *os_release_path
= NULL
;
183 const char *os_release_id
;
186 /* Extracts the metadata from a directory tree 'where'. Extracts two kinds of information: the /etc/os-release
187 * data, and all unit files matching the specified expression. Note that this function is called in two very
188 * different but also similar contexts. When the tool gets invoked on a directory tree, we'll process it
189 * directly, and in-process, and thus can return the requested data directly, via 'ret_os_release' and
190 * 'ret_unit_files'. However, if the tool is invoked on a raw disk image — which needs to be mounted first — we
191 * are invoked in a child process with private mounts and then need to send the collected data to our
192 * parent. To handle both cases in one call this function also gets a 'socket_fd' parameter, which when >= 0 is
193 * used to send the data to the parent. */
197 /* First, find os-release/extension-release and send it upstream (or just save it). */
198 if (path_is_extension
) {
199 os_release_id
= strjoina("/usr/lib/extension-release.d/extension-release.", image_name
);
200 r
= open_extension_release(where
, image_name
, &os_release_path
, &os_release_fd
);
202 os_release_id
= "/etc/os-release";
203 r
= open_os_release(where
, &os_release_path
, &os_release_fd
);
207 "Couldn't acquire %s file, ignoring: %m",
208 path_is_extension
? "extension-release " : "os-release");
210 if (socket_fd
>= 0) {
211 struct iovec iov
[] = {
212 IOVEC_MAKE_STRING(os_release_id
),
213 IOVEC_MAKE((char *)"\0", sizeof(char)),
216 r
= send_one_fd_iov_with_data_fd(socket_fd
, iov
, ELEMENTSOF(iov
), os_release_fd
);
218 return log_debug_errno(r
, "Failed to send os-release file: %m");
221 if (ret_os_release
) {
222 os_release
= portable_metadata_new(os_release_id
, NULL
, NULL
, os_release_fd
);
227 os_release
->source
= TAKE_PTR(os_release_path
);
231 /* Then, send unit file data to the parent (or/and add it to the hashmap). For that we use our usual unit
232 * discovery logic. Note that we force looking inside of /lib/systemd/system/ for units too, as we mightbe
233 * compiled for a split-usr system but the image might be a legacy-usr one. */
234 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, where
);
236 return log_debug_errno(r
, "Failed to acquire lookup paths: %m");
238 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
242 STRV_FOREACH(i
, paths
.search_path
) {
243 _cleanup_free_
char *resolved
= NULL
;
244 _cleanup_closedir_
DIR *d
= NULL
;
246 r
= chase_symlinks_and_opendir(*i
, where
, 0, &resolved
, &d
);
248 log_debug_errno(r
, "Failed to open unit path '%s', ignoring: %m", *i
);
252 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to read directory: %m")) {
253 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*m
= NULL
;
254 _cleanup_(mac_selinux_freep
) char *con
= NULL
;
255 _cleanup_close_
int fd
= -1;
257 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
260 if (!unit_match(de
->d_name
, matches
))
263 /* Filter out duplicates */
264 if (hashmap_get(unit_files
, de
->d_name
))
267 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
270 fd
= openat(dirfd(d
), de
->d_name
, O_CLOEXEC
|O_RDONLY
);
272 log_debug_errno(errno
, "Failed to open unit file '%s', ignoring: %m", de
->d_name
);
277 /* The units will be copied on the host's filesystem, so if they had a SELinux label
278 * we have to preserve it. Copy it out so that it can be applied later. */
280 r
= fgetfilecon_raw(fd
, &con
);
281 if (r
< 0 && errno
!= ENODATA
)
282 log_debug_errno(errno
, "Failed to get SELinux file context from '%s', ignoring: %m", de
->d_name
);
285 if (socket_fd
>= 0) {
286 struct iovec iov
[] = {
287 IOVEC_MAKE_STRING(de
->d_name
),
288 IOVEC_MAKE((char *)"\0", sizeof(char)),
289 IOVEC_MAKE_STRING(strempty(con
)),
292 r
= send_one_fd_iov_with_data_fd(socket_fd
, iov
, ELEMENTSOF(iov
), fd
);
294 return log_debug_errno(r
, "Failed to send unit metadata to parent: %m");
297 m
= portable_metadata_new(de
->d_name
, where
, con
, fd
);
302 m
->source
= path_join(resolved
, de
->d_name
);
306 r
= hashmap_put(unit_files
, m
->name
, m
);
308 return log_debug_errno(r
, "Failed to add unit to hashmap: %m");
314 *ret_os_release
= TAKE_PTR(os_release
);
316 *ret_unit_files
= TAKE_PTR(unit_files
);
321 static int portable_extract_by_path(
323 bool path_is_extension
,
325 PortableMetadata
**ret_os_release
,
326 Hashmap
**ret_unit_files
,
327 sd_bus_error
*error
) {
329 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
330 _cleanup_(portable_metadata_unrefp
) PortableMetadata
* os_release
= NULL
;
331 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
336 r
= loop_device_make_by_path(path
, O_RDONLY
, LO_FLAGS_PARTSCAN
, &d
);
338 _cleanup_free_
char *image_name
= NULL
;
340 /* We can't turn this into a loop-back block device, and this returns EISDIR? Then this is a directory
341 * tree and not a raw device. It's easy then. */
343 r
= path_extract_filename(path
, &image_name
);
345 return log_error_errno(r
, "Failed to extract image name from path '%s': %m", path
);
347 r
= extract_now(path
, matches
, image_name
, path_is_extension
, -1, &os_release
, &unit_files
);
352 return log_debug_errno(r
, "Failed to set up loopback device for %s: %m", path
);
354 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
355 _cleanup_(rmdir_and_freep
) char *tmpdir
= NULL
;
356 _cleanup_(close_pairp
) int seq
[2] = { -1, -1 };
357 _cleanup_(sigkill_waitp
) pid_t child
= 0;
359 /* We now have a loopback block device, let's fork off a child in its own mount namespace, mount it
360 * there, and extract the metadata we need. The metadata is sent from the child back to us. */
362 BLOCK_SIGNALS(SIGCHLD
);
364 r
= mkdtemp_malloc("/tmp/inspect-XXXXXX", &tmpdir
);
366 return log_debug_errno(r
, "Failed to create temporary directory: %m");
372 d
->uevent_seqnum_not_before
,
373 d
->timestamp_not_before
,
374 DISSECT_IMAGE_READ_ONLY
|
375 DISSECT_IMAGE_GENERIC_ROOT
|
376 DISSECT_IMAGE_REQUIRE_ROOT
|
377 DISSECT_IMAGE_DISCARD_ON_LOOP
|
378 DISSECT_IMAGE_RELAX_VAR_CHECK
|
379 DISSECT_IMAGE_USR_NO_ROOT
,
382 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't identify a suitable partition table or file system in '%s'.", path
);
383 else if (r
== -EADDRNOTAVAIL
)
384 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No root partition for specified root hash found in '%s'.", path
);
385 else if (r
== -ENOTUNIQ
)
386 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Multiple suitable root partitions found in image '%s'.", path
);
387 else if (r
== -ENXIO
)
388 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No suitable root partition found in image '%s'.", path
);
389 else if (r
== -EPROTONOSUPPORT
)
390 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Device '%s' is loopback block device with partition scanning turned off, please turn it on.", path
);
394 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, seq
) < 0)
395 return log_debug_errno(errno
, "Failed to allocated SOCK_SEQPACKET socket: %m");
397 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
|FORK_LOG
, &child
);
401 DissectImageFlags flags
= DISSECT_IMAGE_READ_ONLY
;
403 seq
[0] = safe_close(seq
[0]);
405 if (path_is_extension
)
406 flags
|= DISSECT_IMAGE_VALIDATE_OS_EXT
;
408 flags
|= DISSECT_IMAGE_VALIDATE_OS
;
410 r
= dissected_image_mount(m
, tmpdir
, UID_INVALID
, UID_INVALID
, flags
);
412 log_debug_errno(r
, "Failed to mount dissected image: %m");
416 r
= extract_now(tmpdir
, matches
, m
->image_name
, path_is_extension
, seq
[1], NULL
, NULL
);
419 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
422 seq
[1] = safe_close(seq
[1]);
424 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
429 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*add
= NULL
;
430 _cleanup_close_
int fd
= -1;
431 /* We use NAME_MAX space for the SELinux label here. The kernel currently enforces no limit, but
432 * according to suggestions from the SELinux people this will change and it will probably be
433 * identical to NAME_MAX. For now we use that, but this should be updated one day when the final
435 char iov_buffer
[PATH_MAX
+ NAME_MAX
+ 2];
436 struct iovec iov
= IOVEC_INIT(iov_buffer
, sizeof(iov_buffer
));
438 ssize_t n
= receive_one_fd_iov(seq
[0], &iov
, 1, 0, &fd
);
442 return log_debug_errno(n
, "Failed to receive item: %m");
445 /* We can't really distinguish a zero-length datagram without any fds from EOF (both are signalled the
446 * same way by recvmsg()). Hence, accept either as end notification. */
447 if (isempty(iov_buffer
) && fd
< 0)
450 if (isempty(iov_buffer
) || fd
< 0)
451 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
452 "Invalid item sent from child.");
454 /* Given recvmsg cannot be used with multiple io vectors if you don't know the size in advance,
455 * use a marker to separate the name and the optional SELinux context. */
456 char *selinux_label
= memchr(iov_buffer
, 0, n
);
457 assert(selinux_label
);
460 add
= portable_metadata_new(iov_buffer
, path
, selinux_label
, fd
);
465 /* Note that we do not initialize 'add->source' here, as the source path is not usable here as
466 * it refers to a path only valid in the short-living namespaced child process we forked
469 if (PORTABLE_METADATA_IS_UNIT(add
)) {
470 r
= hashmap_put(unit_files
, add
->name
, add
);
472 return log_debug_errno(r
, "Failed to add item to unit file list: %m");
476 } else if (PORTABLE_METADATA_IS_OS_RELEASE(add
) || PORTABLE_METADATA_IS_EXTENSION_RELEASE(add
)) {
479 os_release
= TAKE_PTR(add
);
481 assert_not_reached();
484 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
491 return sd_bus_error_setf(error
,
492 SD_BUS_ERROR_INVALID_ARGS
,
493 "Image '%s' lacks %s data, refusing.",
495 path_is_extension
? "extension-release" : "os-release");
498 *ret_unit_files
= TAKE_PTR(unit_files
);
501 *ret_os_release
= TAKE_PTR(os_release
);
506 static int extract_image_and_extensions(
507 const char *name_or_path
,
509 char **extension_image_paths
,
510 bool validate_sysext
,
512 OrderedHashmap
**ret_extension_images
,
513 OrderedHashmap
**ret_extension_releases
,
514 PortableMetadata
**ret_os_release
,
515 Hashmap
**ret_unit_files
,
516 char ***ret_valid_prefixes
,
517 sd_bus_error
*error
) {
519 _cleanup_free_
char *id
= NULL
, *version_id
= NULL
, *sysext_level
= NULL
;
520 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
521 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
, *extension_releases
= NULL
;
522 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
523 _cleanup_strv_free_
char **valid_prefixes
= NULL
;
524 _cleanup_(image_unrefp
) Image
*image
= NULL
;
528 assert(name_or_path
);
531 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, NULL
, &image
);
535 if (!strv_isempty(extension_image_paths
)) {
536 extension_images
= ordered_hashmap_new(&image_hash_ops
);
537 if (!extension_images
)
540 if (ret_extension_releases
) {
541 extension_releases
= ordered_hashmap_new(&portable_metadata_hash_ops
);
542 if (!extension_releases
)
546 STRV_FOREACH(p
, extension_image_paths
) {
547 _cleanup_(image_unrefp
) Image
*new = NULL
;
549 r
= image_find_harder(IMAGE_PORTABLE
, *p
, NULL
, &new);
553 r
= ordered_hashmap_put(extension_images
, new->name
, new);
560 r
= portable_extract_by_path(image
->path
, /* path_is_extension= */ false, matches
, &os_release
, &unit_files
, error
);
564 /* If we are layering extension images on top of a runtime image, check that the os-release and
565 * extension-release metadata match, otherwise reject it immediately as invalid, or it will fail when
566 * the units are started. Also, collect valid portable prefixes if caller requested that. */
567 if (validate_sysext
|| ret_valid_prefixes
) {
568 _cleanup_fclose_
FILE *f
= NULL
;
569 _cleanup_free_
char *prefixes
= NULL
;
571 r
= take_fdopen_unlocked(&os_release
->fd
, "r", &f
);
575 r
= parse_env_file(f
, os_release
->name
,
577 "VERSION_ID", &version_id
,
578 "SYSEXT_LEVEL", &sysext_level
,
579 "PORTABLE_PREFIXES", &prefixes
);
584 valid_prefixes
= strv_split(prefixes
, WHITESPACE
);
590 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
591 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*extension_release_meta
= NULL
;
592 _cleanup_hashmap_free_ Hashmap
*extra_unit_files
= NULL
;
593 _cleanup_strv_free_
char **extension_release
= NULL
;
594 _cleanup_close_
int extension_release_fd
= -1;
595 _cleanup_fclose_
FILE *f
= NULL
;
598 r
= portable_extract_by_path(ext
->path
, /* path_is_extension= */ true, matches
, &extension_release_meta
, &extra_unit_files
, error
);
602 r
= hashmap_move(unit_files
, extra_unit_files
);
606 if (!validate_sysext
&& !ret_valid_prefixes
&& !ret_extension_releases
)
609 /* We need to keep the fd valid, to return the PortableMetadata to the caller. */
610 extension_release_fd
= fd_reopen(extension_release_meta
->fd
, O_CLOEXEC
|O_RDONLY
);
611 if (extension_release_fd
< 0)
612 return extension_release_fd
;
614 r
= take_fdopen_unlocked(&extension_release_fd
, "r", &f
);
618 r
= load_env_file_pairs(f
, extension_release_meta
->name
, &extension_release
);
622 if (validate_sysext
) {
623 r
= extension_release_validate(ext
->path
, id
, version_id
, sysext_level
, "portable", extension_release
);
625 return sd_bus_error_set_errnof(error
, SYNTHETIC_ERRNO(ESTALE
), "Image %s extension-release metadata does not match the root's", ext
->path
);
627 return sd_bus_error_set_errnof(error
, r
, "Failed to compare image %s extension-release metadata with the root's os-release: %m", ext
->path
);
630 e
= strv_env_pairs_get(extension_release
, "PORTABLE_PREFIXES");
632 _cleanup_strv_free_
char **l
= NULL
;
634 l
= strv_split(e
, WHITESPACE
);
638 r
= strv_extend_strv(&valid_prefixes
, l
, true);
643 if (ret_extension_releases
) {
644 r
= ordered_hashmap_put(extension_releases
, ext
->name
, extension_release_meta
);
647 TAKE_PTR(extension_release_meta
);
651 strv_sort(valid_prefixes
);
654 *ret_image
= TAKE_PTR(image
);
655 if (ret_extension_images
)
656 *ret_extension_images
= TAKE_PTR(extension_images
);
657 if (ret_extension_releases
)
658 *ret_extension_releases
= TAKE_PTR(extension_releases
);
660 *ret_os_release
= TAKE_PTR(os_release
);
662 *ret_unit_files
= TAKE_PTR(unit_files
);
663 if (ret_valid_prefixes
)
664 *ret_valid_prefixes
= TAKE_PTR(valid_prefixes
);
669 int portable_extract(
670 const char *name_or_path
,
672 char **extension_image_paths
,
673 PortableMetadata
**ret_os_release
,
674 OrderedHashmap
**ret_extension_releases
,
675 Hashmap
**ret_unit_files
,
676 char ***ret_valid_prefixes
,
677 sd_bus_error
*error
) {
679 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
680 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
, *extension_releases
= NULL
;
681 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
682 _cleanup_(strv_freep
) char **valid_prefixes
= NULL
;
683 _cleanup_(image_unrefp
) Image
*image
= NULL
;
686 assert(name_or_path
);
688 r
= extract_image_and_extensions(
691 extension_image_paths
,
692 /* validate_sysext= */ false,
698 ret_valid_prefixes
? &valid_prefixes
: NULL
,
703 if (hashmap_isempty(unit_files
)) {
704 _cleanup_free_
char *extensions
= strv_join(extension_image_paths
, ", ");
708 return sd_bus_error_setf(error
,
709 SD_BUS_ERROR_INVALID_ARGS
,
710 "Couldn't find any matching unit files in image '%s%s%s', refusing.",
712 isempty(extensions
) ? "" : "' or any of its extensions '",
713 isempty(extensions
) ? "" : extensions
);
717 *ret_os_release
= TAKE_PTR(os_release
);
718 if (ret_extension_releases
)
719 *ret_extension_releases
= TAKE_PTR(extension_releases
);
721 *ret_unit_files
= TAKE_PTR(unit_files
);
722 if (ret_valid_prefixes
)
723 *ret_valid_prefixes
= TAKE_PTR(valid_prefixes
);
728 static int unit_file_is_active(
731 sd_bus_error
*error
) {
733 static const char *const active_states
[] = {
745 /* If we are looking at a plain or instance things are easy, we can just query the state */
746 if (unit_name_is_valid(name
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
)) {
747 _cleanup_free_
char *path
= NULL
, *buf
= NULL
;
749 path
= unit_dbus_path_from_name(name
);
753 r
= sd_bus_get_property_string(
755 "org.freedesktop.systemd1",
757 "org.freedesktop.systemd1.Unit",
762 return log_debug_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(error
, r
));
764 return strv_contains((char**) active_states
, buf
);
767 /* Otherwise we need to enumerate. But let's build the most restricted query we can */
768 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
769 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
770 const char *at
, *prefix
, *joined
;
772 r
= sd_bus_message_new_method_call(
775 "org.freedesktop.systemd1",
776 "/org/freedesktop/systemd1",
777 "org.freedesktop.systemd1.Manager",
778 "ListUnitsByPatterns");
782 r
= sd_bus_message_append_strv(m
, (char**) active_states
);
786 at
= strchr(name
, '@');
789 prefix
= strndupa_safe(name
, at
+ 1 - name
);
790 joined
= strjoina(prefix
, "*", at
+ 1);
792 r
= sd_bus_message_append_strv(m
, STRV_MAKE(joined
));
796 r
= sd_bus_call(bus
, m
, 0, error
, &reply
);
798 return log_debug_errno(r
, "Failed to list units: %s", bus_error_message(error
, r
));
800 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
804 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_STRUCT
, "ssssssouso");
814 static int portable_changes_add(
815 PortableChange
**changes
,
817 int type_or_errno
, /* PORTABLE_COPY, PORTABLE_SYMLINK, … if positive, or errno if negative */
819 const char *source
) {
821 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
825 assert(!changes
== !n_changes
);
827 if (type_or_errno
>= 0)
828 assert(type_or_errno
< _PORTABLE_CHANGE_TYPE_MAX
);
830 assert(type_or_errno
>= -ERRNO_MAX
);
835 c
= reallocarray(*changes
, *n_changes
+ 1, sizeof(PortableChange
));
854 c
[(*n_changes
)++] = (PortableChange
) {
855 .type_or_errno
= type_or_errno
,
857 .source
= TAKE_PTR(s
),
863 static int portable_changes_add_with_prefix(
864 PortableChange
**changes
,
869 const char *source
) {
872 assert(!changes
== !n_changes
);
878 path
= prefix_roota(prefix
, path
);
881 source
= prefix_roota(prefix
, source
);
884 return portable_changes_add(changes
, n_changes
, type_or_errno
, path
, source
);
887 void portable_changes_free(PortableChange
*changes
, size_t n_changes
) {
890 assert(changes
|| n_changes
== 0);
892 for (i
= 0; i
< n_changes
; i
++) {
893 free(changes
[i
].path
);
894 free(changes
[i
].source
);
900 static const char *root_setting_from_image(ImageType type
) {
901 return IN_SET(type
, IMAGE_DIRECTORY
, IMAGE_SUBVOLUME
) ? "RootDirectory=" : "RootImage=";
904 static const char *extension_setting_from_image(ImageType type
) {
905 return IN_SET(type
, IMAGE_DIRECTORY
, IMAGE_SUBVOLUME
) ? "ExtensionDirectories=" : "ExtensionImages=";
908 static int make_marker_text(const char *image_path
, OrderedHashmap
*extension_images
, char **ret_text
) {
909 _cleanup_free_
char *text
= NULL
, *escaped_image_path
= NULL
;
915 escaped_image_path
= xescape(image_path
, ":");
916 if (!escaped_image_path
)
919 /* If the image is layered, include all layers in the marker as a colon-separated
920 * list of paths, so that we can do exact matches on removal. */
921 text
= strjoin(PORTABLE_DROPIN_MARKER_BEGIN
, escaped_image_path
);
925 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
926 _cleanup_free_
char *escaped
= NULL
;
928 escaped
= xescape(ext
->path
, ":");
932 if (!strextend(&text
, ":", escaped
))
936 if (!strextend(&text
, PORTABLE_DROPIN_MARKER_END
"\n"))
939 *ret_text
= TAKE_PTR(text
);
943 static int install_chroot_dropin(
944 const char *image_path
,
946 OrderedHashmap
*extension_images
,
947 const PortableMetadata
*m
,
948 const char *dropin_dir
,
950 PortableChange
**changes
,
953 _cleanup_free_
char *text
= NULL
, *dropin
= NULL
;
960 dropin
= path_join(dropin_dir
, "20-portable.conf");
964 r
= make_marker_text(image_path
, extension_images
, &text
);
966 return log_debug_errno(r
, "Failed to generate marker string for portable drop-in: %m");
968 if (endswith(m
->name
, ".service")) {
969 const char *os_release_source
, *root_type
;
970 _cleanup_free_
char *base_name
= NULL
;
973 root_type
= root_setting_from_image(type
);
975 if (access("/etc/os-release", F_OK
) < 0) {
977 return log_debug_errno(errno
, "Failed to check if /etc/os-release exists: %m");
979 os_release_source
= "/usr/lib/os-release";
981 os_release_source
= "/etc/os-release";
983 r
= path_extract_filename(m
->image_path
?: image_path
, &base_name
);
985 return log_debug_errno(r
, "Failed to extract basename from '%s': %m", m
->image_path
?: image_path
);
987 if (!strextend(&text
,
990 root_type
, image_path
, "\n"
991 "Environment=PORTABLE=", base_name
, "\n"
992 "BindReadOnlyPaths=", os_release_source
, ":/run/host/os-release\n"
993 "LogExtraFields=PORTABLE=", base_name
, "\n"))
996 if (m
->image_path
&& !path_equal(m
->image_path
, image_path
))
997 ORDERED_HASHMAP_FOREACH(ext
, extension_images
)
998 if (!strextend(&text
, extension_setting_from_image(ext
->type
), ext
->path
, "\n"))
1002 r
= write_string_file(dropin
, text
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
1004 return log_debug_errno(r
, "Failed to write '%s': %m", dropin
);
1006 (void) portable_changes_add(changes
, n_changes
, PORTABLE_WRITE
, dropin
, NULL
);
1009 *ret_dropin
= TAKE_PTR(dropin
);
1014 static int install_profile_dropin(
1015 const char *image_path
,
1016 const PortableMetadata
*m
,
1017 const char *dropin_dir
,
1018 const char *profile
,
1019 PortableFlags flags
,
1021 PortableChange
**changes
,
1022 size_t *n_changes
) {
1024 _cleanup_free_
char *dropin
= NULL
, *from
= NULL
;
1034 r
= find_portable_profile(profile
, m
->name
, &from
);
1037 return log_debug_errno(errno
, "Profile '%s' is not accessible: %m", profile
);
1039 log_debug_errno(errno
, "Skipping link to profile '%s', as it does not exist: %m", profile
);
1043 dropin
= path_join(dropin_dir
, "10-profile.conf");
1047 if (flags
& PORTABLE_PREFER_COPY
) {
1049 r
= copy_file_atomic(from
, dropin
, 0644, 0, 0, COPY_REFLINK
);
1051 return log_debug_errno(r
, "Failed to copy %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), dropin
);
1053 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, dropin
, from
);
1057 if (symlink(from
, dropin
) < 0)
1058 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), dropin
);
1060 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, dropin
, from
);
1064 *ret_dropin
= TAKE_PTR(dropin
);
1069 static const char *attached_path(const LookupPaths
*paths
, PortableFlags flags
) {
1074 if (flags
& PORTABLE_RUNTIME
)
1075 where
= paths
->runtime_attached
;
1077 where
= paths
->persistent_attached
;
1083 static int attach_unit_file(
1084 const LookupPaths
*paths
,
1085 const char *image_path
,
1087 OrderedHashmap
*extension_images
,
1088 const PortableMetadata
*m
,
1089 const char *profile
,
1090 PortableFlags flags
,
1091 PortableChange
**changes
,
1092 size_t *n_changes
) {
1094 _cleanup_(unlink_and_freep
) char *chroot_dropin
= NULL
, *profile_dropin
= NULL
;
1095 _cleanup_(rmdir_and_freep
) char *dropin_dir
= NULL
;
1096 const char *where
, *path
;
1102 assert(PORTABLE_METADATA_IS_UNIT(m
));
1104 where
= attached_path(paths
, flags
);
1106 (void) mkdir_parents(where
, 0755);
1107 if (mkdir(where
, 0755) < 0) {
1108 if (errno
!= EEXIST
)
1111 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, where
, NULL
);
1113 path
= prefix_roota(where
, m
->name
);
1114 dropin_dir
= strjoin(path
, ".d");
1118 if (mkdir(dropin_dir
, 0755) < 0) {
1119 if (errno
!= EEXIST
)
1122 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, dropin_dir
, NULL
);
1124 /* We install the drop-ins first, and the actual unit file last to achieve somewhat atomic behaviour if PID 1
1125 * is reloaded while we are creating things here: as long as only the drop-ins exist the unit doesn't exist at
1128 r
= install_chroot_dropin(image_path
, type
, extension_images
, m
, dropin_dir
, &chroot_dropin
, changes
, n_changes
);
1132 r
= install_profile_dropin(image_path
, m
, dropin_dir
, profile
, flags
, &profile_dropin
, changes
, n_changes
);
1136 if ((flags
& PORTABLE_PREFER_SYMLINK
) && m
->source
) {
1138 if (symlink(m
->source
, path
) < 0)
1139 return log_debug_errno(errno
, "Failed to symlink unit file '%s': %m", path
);
1141 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, path
, m
->source
);
1144 _cleanup_(unlink_and_freep
) char *tmp
= NULL
;
1145 _cleanup_close_
int fd
= -1;
1147 (void) mac_selinux_create_file_prepare_label(path
, m
->selinux_label
);
1149 fd
= open_tmpfile_linkable(path
, O_WRONLY
|O_CLOEXEC
, &tmp
);
1150 mac_selinux_create_file_clear(); /* Clear immediately in case of errors */
1152 return log_debug_errno(fd
, "Failed to create unit file '%s': %m", path
);
1154 r
= copy_bytes(m
->fd
, fd
, UINT64_MAX
, COPY_REFLINK
);
1156 return log_debug_errno(r
, "Failed to copy unit file '%s': %m", path
);
1158 if (fchmod(fd
, 0644) < 0)
1159 return log_debug_errno(errno
, "Failed to change unit file access mode for '%s': %m", path
);
1161 r
= link_tmpfile(fd
, tmp
, path
);
1163 return log_debug_errno(r
, "Failed to install unit file '%s': %m", path
);
1167 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, path
, m
->source
);
1170 /* All is established now, now let's disable any rollbacks */
1171 chroot_dropin
= mfree(chroot_dropin
);
1172 profile_dropin
= mfree(profile_dropin
);
1173 dropin_dir
= mfree(dropin_dir
);
1178 static int image_symlink(
1179 const char *image_path
,
1180 PortableFlags flags
,
1183 const char *fn
, *where
;
1184 char *joined
= NULL
;
1189 fn
= last_path_component(image_path
);
1191 if (flags
& PORTABLE_RUNTIME
)
1192 where
= "/run/portables/";
1194 where
= "/etc/portables/";
1196 joined
= strjoin(where
, fn
);
1204 static int install_image_symlink(
1205 const char *image_path
,
1206 PortableFlags flags
,
1207 PortableChange
**changes
,
1208 size_t *n_changes
) {
1210 _cleanup_free_
char *sl
= NULL
;
1215 /* If the image is outside of the image search also link it into it, so that it can be found with short image
1216 * names and is listed among the images. */
1218 if (image_in_search_path(IMAGE_PORTABLE
, NULL
, image_path
))
1221 r
= image_symlink(image_path
, flags
, &sl
);
1223 return log_debug_errno(r
, "Failed to generate image symlink path: %m");
1225 (void) mkdir_parents(sl
, 0755);
1227 if (symlink(image_path
, sl
) < 0)
1228 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", image_path
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), sl
);
1230 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, sl
, image_path
);
1234 static int install_image_and_extensions_symlinks(
1236 OrderedHashmap
*extension_images
,
1237 PortableFlags flags
,
1238 PortableChange
**changes
,
1239 size_t *n_changes
) {
1246 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
1247 r
= install_image_symlink(ext
->path
, flags
, changes
, n_changes
);
1252 r
= install_image_symlink(image
->path
, flags
, changes
, n_changes
);
1259 static bool prefix_matches_compatible(char **matches
, char **valid_prefixes
) {
1260 /* Checks if all 'matches' are included in the list of 'valid_prefixes' */
1262 STRV_FOREACH(m
, matches
)
1263 if (!strv_contains(valid_prefixes
, *m
))
1269 int portable_attach(
1271 const char *name_or_path
,
1273 const char *profile
,
1274 char **extension_image_paths
,
1275 PortableFlags flags
,
1276 PortableChange
**changes
,
1278 sd_bus_error
*error
) {
1280 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
;
1281 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
1282 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1283 _cleanup_strv_free_
char **valid_prefixes
= NULL
;
1284 _cleanup_(image_unrefp
) Image
*image
= NULL
;
1285 PortableMetadata
*item
;
1288 r
= extract_image_and_extensions(
1291 extension_image_paths
,
1292 /* validate_sysext= */ true,
1295 /* extension_releases= */ NULL
,
1296 /* os_release= */ NULL
,
1303 if (valid_prefixes
&& !prefix_matches_compatible(matches
, valid_prefixes
)) {
1304 _cleanup_free_
char *matches_joined
= NULL
, *extensions_joined
= NULL
, *valid_prefixes_joined
= NULL
;
1306 matches_joined
= strv_join(matches
, "', '");
1307 if (!matches_joined
)
1310 extensions_joined
= strv_join(extension_image_paths
, ", ");
1311 if (!extensions_joined
)
1314 valid_prefixes_joined
= strv_join(valid_prefixes
, ", ");
1315 if (!valid_prefixes_joined
)
1318 return sd_bus_error_setf(
1320 SD_BUS_ERROR_INVALID_ARGS
,
1321 "Selected matches '%s' are not compatible with portable service image '%s%s%s', refusing. (Acceptable prefix matches are: %s)",
1324 isempty(extensions_joined
) ? "" : "' or any of its extensions '",
1325 strempty(extensions_joined
),
1326 valid_prefixes_joined
);
1329 if (hashmap_isempty(unit_files
)) {
1330 _cleanup_free_
char *extensions_joined
= strv_join(extension_image_paths
, ", ");
1331 if (!extensions_joined
)
1334 return sd_bus_error_setf(
1336 SD_BUS_ERROR_INVALID_ARGS
,
1337 "Couldn't find any matching unit files in image '%s%s%s', refusing.",
1339 isempty(extensions_joined
) ? "" : "' or any of its extensions '",
1340 strempty(extensions_joined
));
1343 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1347 HASHMAP_FOREACH(item
, unit_files
) {
1348 r
= unit_file_exists(UNIT_FILE_SYSTEM
, &paths
, item
->name
);
1350 return sd_bus_error_set_errnof(error
, r
, "Failed to determine whether unit '%s' exists on the host: %m", item
->name
);
1351 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1352 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' exists on the host already, refusing.", item
->name
);
1354 r
= unit_file_is_active(bus
, item
->name
, error
);
1357 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1358 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active already, refusing.", item
->name
);
1361 HASHMAP_FOREACH(item
, unit_files
) {
1362 r
= attach_unit_file(&paths
, image
->path
, image
->type
, extension_images
,
1363 item
, profile
, flags
, changes
, n_changes
);
1368 /* We don't care too much for the image symlink, it's just a convenience thing, it's not necessary for proper
1369 * operation otherwise. */
1370 (void) install_image_and_extensions_symlinks(image
, extension_images
, flags
, changes
, n_changes
);
1375 static bool marker_matches_images(const char *marker
, const char *name_or_path
, char **extension_image_paths
) {
1376 _cleanup_strv_free_
char **root_and_extensions
= NULL
;
1381 assert(name_or_path
);
1383 /* If extensions were used when attaching, the marker will be a colon-separated
1384 * list of images/paths. We enforce strict 1:1 matching, so that we are sure
1385 * we are detaching exactly what was attached.
1386 * For each image, starting with the root, we look for a token in the marker,
1387 * and return a negative answer on any non-matching combination. */
1389 root_and_extensions
= strv_new(name_or_path
);
1390 if (!root_and_extensions
)
1393 r
= strv_extend_strv(&root_and_extensions
, extension_image_paths
, false);
1397 STRV_FOREACH(image_name_or_path
, root_and_extensions
) {
1398 _cleanup_free_
char *image
= NULL
;
1400 r
= extract_first_word(&marker
, &image
, ":", EXTRACT_UNQUOTE
|EXTRACT_RETAIN_ESCAPE
);
1402 return log_debug_errno(r
, "Failed to parse marker: %s", marker
);
1406 a
= last_path_component(image
);
1408 if (image_name_is_valid(*image_name_or_path
)) {
1409 const char *e
, *underscore
;
1411 /* We shall match against an image name. In that case let's compare the last component, and optionally
1412 * allow either a suffix of ".raw" or a series of "/".
1413 * But allow matching on a different version of the same image, when a "_" is used as a separator. */
1414 underscore
= strchr(*image_name_or_path
, '_');
1416 if (strneq(a
, *image_name_or_path
, underscore
- *image_name_or_path
))
1421 e
= startswith(a
, *image_name_or_path
);
1425 if(!(e
[strspn(e
, "/")] == 0 || streq(e
, ".raw")))
1428 const char *b
, *underscore
;
1431 /* We shall match against a path. Let's ignore any prefix here though, as often there are many ways to
1432 * reach the same file. However, in this mode, let's validate any file suffix. */
1434 l
= strcspn(a
, "/");
1435 b
= last_path_component(*image_name_or_path
);
1437 if (strcspn(b
, "/") != l
)
1440 underscore
= strchr(b
, '_');
1444 if (!strneq(a
, b
, l
))
1452 static int test_chroot_dropin(
1456 const char *name_or_path
,
1457 char **extension_image_paths
,
1458 char **ret_marker
) {
1460 _cleanup_free_
char *line
= NULL
, *marker
= NULL
;
1461 _cleanup_fclose_
FILE *f
= NULL
;
1462 _cleanup_close_
int fd
= -1;
1463 const char *p
, *e
, *k
;
1470 /* We recognize unis created from portable images via the drop-in we created for them */
1472 p
= strjoina(fname
, ".d/20-portable.conf");
1473 fd
= openat(dirfd(d
), p
, O_RDONLY
|O_CLOEXEC
);
1475 if (errno
== ENOENT
)
1478 return log_debug_errno(errno
, "Failed to open %s/%s: %m", where
, p
);
1481 r
= take_fdopen_unlocked(&fd
, "r", &f
);
1483 return log_debug_errno(r
, "Failed to convert file handle: %m");
1485 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1487 return log_debug_errno(r
, "Failed to read from %s/%s: %m", where
, p
);
1489 e
= startswith(line
, PORTABLE_DROPIN_MARKER_BEGIN
);
1493 k
= endswith(e
, PORTABLE_DROPIN_MARKER_END
);
1497 marker
= strndup(e
, k
- e
);
1504 r
= marker_matches_images(marker
, name_or_path
, extension_image_paths
);
1507 *ret_marker
= TAKE_PTR(marker
);
1512 int portable_detach(
1514 const char *name_or_path
,
1515 char **extension_image_paths
,
1516 PortableFlags flags
,
1517 PortableChange
**changes
,
1519 sd_bus_error
*error
) {
1521 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1522 _cleanup_set_free_ Set
*unit_files
= NULL
, *markers
= NULL
;
1523 _cleanup_closedir_
DIR *d
= NULL
;
1524 const char *where
, *item
;
1528 assert(name_or_path
);
1530 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1534 where
= attached_path(&paths
, flags
);
1538 if (errno
== ENOENT
)
1541 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1544 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1545 _cleanup_free_
char *marker
= NULL
;
1546 UnitFileState state
;
1548 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1551 /* Filter out duplicates */
1552 if (set_contains(unit_files
, de
->d_name
))
1555 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1558 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, extension_image_paths
, &marker
);
1564 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1566 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1567 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_RUNTIME
, UNIT_FILE_LINKED_RUNTIME
))
1568 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is in state '%s', can't detach.", de
->d_name
, unit_file_state_to_string(state
));
1570 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1573 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1574 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active, can't detach.", de
->d_name
);
1576 r
= set_put_strdup(&unit_files
, de
->d_name
);
1578 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1580 for (const char *p
= marker
;;) {
1581 _cleanup_free_
char *image
= NULL
;
1583 r
= extract_first_word(&p
, &image
, ":", EXTRACT_UNESCAPE_SEPARATORS
|EXTRACT_RETAIN_ESCAPE
);
1585 return log_debug_errno(r
, "Failed to parse marker: %s", p
);
1589 if (path_is_absolute(image
) && !image_in_search_path(IMAGE_PORTABLE
, NULL
, image
)) {
1590 r
= set_ensure_consume(&markers
, &path_hash_ops_free
, TAKE_PTR(image
));
1597 if (set_isempty(unit_files
))
1600 SET_FOREACH(item
, unit_files
) {
1601 _cleanup_free_
char *md
= NULL
;
1604 if (unlinkat(dirfd(d
), item
, 0) < 0) {
1605 log_debug_errno(errno
, "Can't remove unit file %s/%s: %m", where
, item
);
1607 if (errno
!= ENOENT
&& ret
>= 0)
1610 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, item
, NULL
);
1612 FOREACH_STRING(suffix
, ".d/10-profile.conf", ".d/20-portable.conf") {
1613 _cleanup_free_
char *dropin
= NULL
;
1615 dropin
= strjoin(item
, suffix
);
1619 if (unlinkat(dirfd(d
), dropin
, 0) < 0) {
1620 log_debug_errno(errno
, "Can't remove drop-in %s/%s: %m", where
, dropin
);
1622 if (errno
!= ENOENT
&& ret
>= 0)
1625 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, dropin
, NULL
);
1628 md
= strjoin(item
, ".d");
1632 if (unlinkat(dirfd(d
), md
, AT_REMOVEDIR
) < 0) {
1633 log_debug_errno(errno
, "Can't remove drop-in directory %s/%s: %m", where
, md
);
1635 if (errno
!= ENOENT
&& ret
>= 0)
1638 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, md
, NULL
);
1641 /* Now, also drop any image symlink, for images outside of the sarch path */
1642 SET_FOREACH(item
, markers
) {
1643 _cleanup_free_
char *sl
= NULL
;
1646 r
= image_symlink(item
, flags
, &sl
);
1648 log_debug_errno(r
, "Failed to determine image symlink for '%s', ignoring: %m", item
);
1652 if (lstat(sl
, &st
) < 0) {
1653 log_debug_errno(errno
, "Failed to stat '%s', ignoring: %m", sl
);
1657 if (!S_ISLNK(st
.st_mode
)) {
1658 log_debug("Image '%s' is not a symlink, ignoring.", sl
);
1662 if (unlink(sl
) < 0) {
1663 log_debug_errno(errno
, "Can't remove image symlink '%s': %m", sl
);
1665 if (errno
!= ENOENT
&& ret
>= 0)
1668 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, sl
, NULL
);
1671 /* Try to remove the unit file directory, if we can */
1672 if (rmdir(where
) >= 0)
1673 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, where
, NULL
);
1678 log_debug("No unit files associated with '%s' found. Image not attached?", name_or_path
);
1679 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_UNIT
, "No unit files associated with '%s' found. Image not attached?", name_or_path
);
1682 static int portable_get_state_internal(
1684 const char *name_or_path
,
1685 char **extension_image_paths
,
1686 PortableFlags flags
,
1688 sd_bus_error
*error
) {
1690 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1691 bool found_enabled
= false, found_running
= false;
1692 _cleanup_set_free_ Set
*unit_files
= NULL
;
1693 _cleanup_closedir_
DIR *d
= NULL
;
1697 assert(name_or_path
);
1700 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1704 where
= attached_path(&paths
, flags
);
1708 if (errno
== ENOENT
) {
1709 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1710 *ret
= PORTABLE_DETACHED
;
1714 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1717 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1718 UnitFileState state
;
1720 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1723 /* Filter out duplicates */
1724 if (set_contains(unit_files
, de
->d_name
))
1727 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1730 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, extension_image_paths
, NULL
);
1736 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1738 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1739 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_LINKED_RUNTIME
))
1740 found_enabled
= true;
1742 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1746 found_running
= true;
1748 r
= set_put_strdup(&unit_files
, de
->d_name
);
1750 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1753 *ret
= found_running
? (!set_isempty(unit_files
) && (flags
& PORTABLE_RUNTIME
) ? PORTABLE_RUNNING_RUNTIME
: PORTABLE_RUNNING
) :
1754 found_enabled
? (flags
& PORTABLE_RUNTIME
? PORTABLE_ENABLED_RUNTIME
: PORTABLE_ENABLED
) :
1755 !set_isempty(unit_files
) ? (flags
& PORTABLE_RUNTIME
? PORTABLE_ATTACHED_RUNTIME
: PORTABLE_ATTACHED
) : PORTABLE_DETACHED
;
1760 int portable_get_state(
1762 const char *name_or_path
,
1763 char **extension_image_paths
,
1764 PortableFlags flags
,
1766 sd_bus_error
*error
) {
1768 PortableState state
;
1771 assert(name_or_path
);
1774 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1775 * the latter only if we didn't find anything in the former. */
1777 r
= portable_get_state_internal(bus
, name_or_path
, extension_image_paths
, flags
& ~PORTABLE_RUNTIME
, &state
, error
);
1781 if (state
== PORTABLE_DETACHED
) {
1782 r
= portable_get_state_internal(bus
, name_or_path
, extension_image_paths
, flags
| PORTABLE_RUNTIME
, &state
, error
);
1791 int portable_get_profiles(char ***ret
) {
1794 return conf_files_list_nulstr(ret
, NULL
, NULL
, CONF_FILES_DIRECTORY
|CONF_FILES_BASENAME
|CONF_FILES_FILTER_MASKED
, PORTABLE_PROFILE_DIRS
);
1797 static const char* const portable_change_type_table
[_PORTABLE_CHANGE_TYPE_MAX
] = {
1798 [PORTABLE_COPY
] = "copy",
1799 [PORTABLE_MKDIR
] = "mkdir",
1800 [PORTABLE_SYMLINK
] = "symlink",
1801 [PORTABLE_UNLINK
] = "unlink",
1802 [PORTABLE_WRITE
] = "write",
1805 DEFINE_STRING_TABLE_LOOKUP(portable_change_type
, int);
1807 static const char* const portable_state_table
[_PORTABLE_STATE_MAX
] = {
1808 [PORTABLE_DETACHED
] = "detached",
1809 [PORTABLE_ATTACHED
] = "attached",
1810 [PORTABLE_ATTACHED_RUNTIME
] = "attached-runtime",
1811 [PORTABLE_ENABLED
] = "enabled",
1812 [PORTABLE_ENABLED_RUNTIME
] = "enabled-runtime",
1813 [PORTABLE_RUNNING
] = "running",
1814 [PORTABLE_RUNNING_RUNTIME
] = "running-runtime",
1817 DEFINE_STRING_TABLE_LOOKUP(portable_state
, PortableState
);