1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <linux/loop.h>
5 #include "bus-common-errors.h"
8 #include "conf-files.h"
10 #include "data-fd-util.h"
11 #include "constants.h"
12 #include "dirent-util.h"
13 #include "discover-image.h"
14 #include "dissect-image.h"
17 #include "errno-list.h"
19 #include "extension-util.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
= -EBADF
;
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
,
174 bool relax_extension_release_check
,
176 PortableMetadata
**ret_os_release
,
177 Hashmap
**ret_unit_files
) {
179 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
180 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
181 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
182 _cleanup_close_
int os_release_fd
= -EBADF
;
183 _cleanup_free_
char *os_release_path
= NULL
;
184 const char *os_release_id
;
187 /* Extracts the metadata from a directory tree 'where'. Extracts two kinds of information: the /etc/os-release
188 * data, and all unit files matching the specified expression. Note that this function is called in two very
189 * different but also similar contexts. When the tool gets invoked on a directory tree, we'll process it
190 * directly, and in-process, and thus can return the requested data directly, via 'ret_os_release' and
191 * 'ret_unit_files'. However, if the tool is invoked on a raw disk image — which needs to be mounted first — we
192 * are invoked in a child process with private mounts and then need to send the collected data to our
193 * parent. To handle both cases in one call this function also gets a 'socket_fd' parameter, which when >= 0 is
194 * used to send the data to the parent. */
198 /* First, find os-release/extension-release and send it upstream (or just save it). */
199 if (path_is_extension
) {
200 os_release_id
= strjoina("/usr/lib/extension-release.d/extension-release.", image_name
);
201 r
= open_extension_release(where
, image_name
, relax_extension_release_check
, &os_release_path
, &os_release_fd
);
203 os_release_id
= "/etc/os-release";
204 r
= open_os_release(where
, &os_release_path
, &os_release_fd
);
208 "Couldn't acquire %s file, ignoring: %m",
209 path_is_extension
? "extension-release " : "os-release");
211 if (socket_fd
>= 0) {
212 struct iovec iov
[] = {
213 IOVEC_MAKE_STRING(os_release_id
),
214 IOVEC_MAKE((char *)"\0", sizeof(char)),
217 r
= send_one_fd_iov_with_data_fd(socket_fd
, iov
, ELEMENTSOF(iov
), os_release_fd
);
219 return log_debug_errno(r
, "Failed to send os-release file: %m");
222 if (ret_os_release
) {
223 os_release
= portable_metadata_new(os_release_id
, NULL
, NULL
, os_release_fd
);
227 os_release_fd
= -EBADF
;
228 os_release
->source
= TAKE_PTR(os_release_path
);
232 /* Then, send unit file data to the parent (or/and add it to the hashmap). For that we use our usual unit
233 * discovery logic. Note that we force looking inside of /lib/systemd/system/ for units too, as we mightbe
234 * compiled for a split-usr system but the image might be a legacy-usr one. */
235 r
= lookup_paths_init(&paths
, RUNTIME_SCOPE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, where
);
237 return log_debug_errno(r
, "Failed to acquire lookup paths: %m");
239 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
243 STRV_FOREACH(i
, paths
.search_path
) {
244 _cleanup_free_
char *resolved
= NULL
;
245 _cleanup_closedir_
DIR *d
= NULL
;
247 r
= chase_and_opendir(*i
, where
, 0, &resolved
, &d
);
249 log_debug_errno(r
, "Failed to open unit path '%s', ignoring: %m", *i
);
253 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to read directory: %m")) {
254 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*m
= NULL
;
255 _cleanup_(mac_selinux_freep
) char *con
= NULL
;
256 _cleanup_close_
int fd
= -EBADF
;
258 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
261 if (!unit_match(de
->d_name
, matches
))
264 /* Filter out duplicates */
265 if (hashmap_get(unit_files
, de
->d_name
))
268 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
271 fd
= openat(dirfd(d
), de
->d_name
, O_CLOEXEC
|O_RDONLY
);
273 log_debug_errno(errno
, "Failed to open unit file '%s', ignoring: %m", de
->d_name
);
278 /* The units will be copied on the host's filesystem, so if they had a SELinux label
279 * we have to preserve it. Copy it out so that it can be applied later. */
281 r
= fgetfilecon_raw(fd
, &con
);
282 if (r
< 0 && !ERRNO_IS_XATTR_ABSENT(errno
))
283 log_debug_errno(errno
, "Failed to get SELinux file context from '%s', ignoring: %m", de
->d_name
);
286 if (socket_fd
>= 0) {
287 struct iovec iov
[] = {
288 IOVEC_MAKE_STRING(de
->d_name
),
289 IOVEC_MAKE((char *)"\0", sizeof(char)),
290 IOVEC_MAKE_STRING(strempty(con
)),
293 r
= send_one_fd_iov_with_data_fd(socket_fd
, iov
, ELEMENTSOF(iov
), fd
);
295 return log_debug_errno(r
, "Failed to send unit metadata to parent: %m");
298 m
= portable_metadata_new(de
->d_name
, where
, con
, fd
);
303 m
->source
= path_join(resolved
, de
->d_name
);
307 r
= hashmap_put(unit_files
, m
->name
, m
);
309 return log_debug_errno(r
, "Failed to add unit to hashmap: %m");
315 *ret_os_release
= TAKE_PTR(os_release
);
317 *ret_unit_files
= TAKE_PTR(unit_files
);
322 static int portable_extract_by_path(
324 bool path_is_extension
,
325 bool relax_extension_release_check
,
327 PortableMetadata
**ret_os_release
,
328 Hashmap
**ret_unit_files
,
329 sd_bus_error
*error
) {
331 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
332 _cleanup_(portable_metadata_unrefp
) PortableMetadata
* os_release
= NULL
;
333 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
338 r
= loop_device_make_by_path(path
, O_RDONLY
, /* sector_size= */ UINT32_MAX
, LO_FLAGS_PARTSCAN
, LOCK_SH
, &d
);
340 _cleanup_free_
char *image_name
= NULL
;
342 /* We can't turn this into a loop-back block device, and this returns EISDIR? Then this is a directory
343 * tree and not a raw device. It's easy then. */
345 r
= path_extract_filename(path
, &image_name
);
347 return log_error_errno(r
, "Failed to extract image name from path '%s': %m", path
);
349 r
= extract_now(path
, matches
, image_name
, path_is_extension
, /* relax_extension_release_check= */ false, -1, &os_release
, &unit_files
);
354 return log_debug_errno(r
, "Failed to set up loopback device for %s: %m", path
);
356 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
357 _cleanup_(rmdir_and_freep
) char *tmpdir
= NULL
;
358 _cleanup_(close_pairp
) int seq
[2] = PIPE_EBADF
;
359 _cleanup_(sigkill_waitp
) pid_t child
= 0;
361 /* We now have a loopback block device, let's fork off a child in its own mount namespace, mount it
362 * there, and extract the metadata we need. The metadata is sent from the child back to us. */
364 BLOCK_SIGNALS(SIGCHLD
);
366 r
= mkdtemp_malloc("/tmp/inspect-XXXXXX", &tmpdir
);
368 return log_debug_errno(r
, "Failed to create temporary directory: %m");
370 r
= dissect_loop_device(
373 DISSECT_IMAGE_READ_ONLY
|
374 DISSECT_IMAGE_GENERIC_ROOT
|
375 DISSECT_IMAGE_REQUIRE_ROOT
|
376 DISSECT_IMAGE_DISCARD_ON_LOOP
|
377 DISSECT_IMAGE_RELAX_VAR_CHECK
|
378 DISSECT_IMAGE_USR_NO_ROOT
|
379 DISSECT_IMAGE_ADD_PARTITION_DEVICES
|
380 DISSECT_IMAGE_PIN_PARTITION_DEVICES
,
383 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't identify a suitable partition table or file system in '%s'.", path
);
384 else if (r
== -EADDRNOTAVAIL
)
385 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No root partition for specified root hash found in '%s'.", path
);
386 else if (r
== -ENOTUNIQ
)
387 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Multiple suitable root partitions found in image '%s'.", path
);
388 else if (r
== -ENXIO
)
389 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No suitable root partition found in image '%s'.", path
);
390 else if (r
== -EPROTONOSUPPORT
)
391 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
);
395 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, seq
) < 0)
396 return log_debug_errno(errno
, "Failed to allocated SOCK_SEQPACKET socket: %m");
398 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
|FORK_LOG
, &child
);
402 DissectImageFlags flags
= DISSECT_IMAGE_READ_ONLY
;
404 seq
[0] = safe_close(seq
[0]);
406 if (path_is_extension
)
407 flags
|= DISSECT_IMAGE_VALIDATE_OS_EXT
| (relax_extension_release_check
? DISSECT_IMAGE_RELAX_SYSEXT_CHECK
: 0);
409 flags
|= DISSECT_IMAGE_VALIDATE_OS
;
411 r
= dissected_image_mount(m
, tmpdir
, UID_INVALID
, UID_INVALID
, flags
);
413 log_debug_errno(r
, "Failed to mount dissected image: %m");
417 r
= extract_now(tmpdir
, matches
, m
->image_name
, path_is_extension
, relax_extension_release_check
, seq
[1], NULL
, NULL
);
420 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
423 seq
[1] = safe_close(seq
[1]);
425 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
430 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*add
= NULL
;
431 _cleanup_close_
int fd
= -EBADF
;
432 /* We use NAME_MAX space for the SELinux label here. The kernel currently enforces no limit, but
433 * according to suggestions from the SELinux people this will change and it will probably be
434 * identical to NAME_MAX. For now we use that, but this should be updated one day when the final
436 char iov_buffer
[PATH_MAX
+ NAME_MAX
+ 2];
437 struct iovec iov
= IOVEC_MAKE(iov_buffer
, sizeof(iov_buffer
));
439 ssize_t n
= receive_one_fd_iov(seq
[0], &iov
, 1, 0, &fd
);
443 return log_debug_errno(n
, "Failed to receive item: %m");
446 /* We can't really distinguish a zero-length datagram without any fds from EOF (both are signalled the
447 * same way by recvmsg()). Hence, accept either as end notification. */
448 if (isempty(iov_buffer
) && fd
< 0)
451 if (isempty(iov_buffer
) || fd
< 0)
452 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
453 "Invalid item sent from child.");
455 /* Given recvmsg cannot be used with multiple io vectors if you don't know the size in advance,
456 * use a marker to separate the name and the optional SELinux context. */
457 char *selinux_label
= memchr(iov_buffer
, 0, n
);
458 assert(selinux_label
);
461 add
= portable_metadata_new(iov_buffer
, path
, selinux_label
, fd
);
466 /* Note that we do not initialize 'add->source' here, as the source path is not usable here as
467 * it refers to a path only valid in the short-living namespaced child process we forked
470 if (PORTABLE_METADATA_IS_UNIT(add
)) {
471 r
= hashmap_put(unit_files
, add
->name
, add
);
473 return log_debug_errno(r
, "Failed to add item to unit file list: %m");
477 } else if (PORTABLE_METADATA_IS_OS_RELEASE(add
) || PORTABLE_METADATA_IS_EXTENSION_RELEASE(add
)) {
480 os_release
= TAKE_PTR(add
);
482 assert_not_reached();
485 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
492 return sd_bus_error_setf(error
,
493 SD_BUS_ERROR_INVALID_ARGS
,
494 "Image '%s' lacks %s data, refusing.",
496 path_is_extension
? "extension-release" : "os-release");
499 *ret_unit_files
= TAKE_PTR(unit_files
);
502 *ret_os_release
= TAKE_PTR(os_release
);
507 static int extract_image_and_extensions(
508 const char *name_or_path
,
510 char **extension_image_paths
,
511 bool validate_sysext
,
512 bool relax_extension_release_check
,
514 OrderedHashmap
**ret_extension_images
,
515 OrderedHashmap
**ret_extension_releases
,
516 PortableMetadata
**ret_os_release
,
517 Hashmap
**ret_unit_files
,
518 char ***ret_valid_prefixes
,
519 sd_bus_error
*error
) {
521 _cleanup_free_
char *id
= NULL
, *version_id
= NULL
, *sysext_level
= NULL
;
522 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
523 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
, *extension_releases
= NULL
;
524 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
525 _cleanup_strv_free_
char **valid_prefixes
= NULL
;
526 _cleanup_(image_unrefp
) Image
*image
= NULL
;
530 assert(name_or_path
);
532 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, NULL
, &image
);
536 if (!strv_isempty(extension_image_paths
)) {
537 extension_images
= ordered_hashmap_new(&image_hash_ops
);
538 if (!extension_images
)
541 if (ret_extension_releases
) {
542 extension_releases
= ordered_hashmap_new(&portable_metadata_hash_ops
);
543 if (!extension_releases
)
547 STRV_FOREACH(p
, extension_image_paths
) {
548 _cleanup_(image_unrefp
) Image
*new = NULL
;
550 r
= image_find_harder(IMAGE_PORTABLE
, *p
, NULL
, &new);
554 r
= ordered_hashmap_put(extension_images
, new->name
, new);
561 r
= portable_extract_by_path(image
->path
, /* path_is_extension= */ false, /* relax_extension_release_check= */ false, matches
, &os_release
, &unit_files
, error
);
565 /* If we are layering extension images on top of a runtime image, check that the os-release and
566 * extension-release metadata match, otherwise reject it immediately as invalid, or it will fail when
567 * the units are started. Also, collect valid portable prefixes if caller requested that. */
568 if (validate_sysext
|| ret_valid_prefixes
) {
569 _cleanup_free_
char *prefixes
= NULL
;
571 r
= parse_env_file_fd(os_release
->fd
, os_release
->name
,
573 "VERSION_ID", &version_id
,
574 "SYSEXT_LEVEL", &sysext_level
,
575 "PORTABLE_PREFIXES", &prefixes
);
579 return sd_bus_error_set_errnof(error
, SYNTHETIC_ERRNO(ESTALE
), "Image %s os-release metadata lacks the ID field", name_or_path
);
582 valid_prefixes
= strv_split(prefixes
, WHITESPACE
);
588 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
589 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*extension_release_meta
= NULL
;
590 _cleanup_hashmap_free_ Hashmap
*extra_unit_files
= NULL
;
591 _cleanup_strv_free_
char **extension_release
= NULL
;
594 r
= portable_extract_by_path(ext
->path
, /* path_is_extension= */ true, relax_extension_release_check
, matches
, &extension_release_meta
, &extra_unit_files
, error
);
598 r
= hashmap_move(unit_files
, extra_unit_files
);
602 if (!validate_sysext
&& !ret_valid_prefixes
&& !ret_extension_releases
)
605 r
= load_env_file_pairs_fd(extension_release_meta
->fd
, extension_release_meta
->name
, &extension_release
);
609 if (validate_sysext
) {
610 r
= extension_release_validate(ext
->path
, id
, version_id
, sysext_level
, "portable", extension_release
);
612 return sd_bus_error_set_errnof(error
, SYNTHETIC_ERRNO(ESTALE
), "Image %s extension-release metadata does not match the root's", ext
->path
);
614 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
);
617 e
= strv_env_pairs_get(extension_release
, "PORTABLE_PREFIXES");
619 _cleanup_strv_free_
char **l
= NULL
;
621 l
= strv_split(e
, WHITESPACE
);
625 r
= strv_extend_strv(&valid_prefixes
, l
, true);
630 if (ret_extension_releases
) {
631 r
= ordered_hashmap_put(extension_releases
, ext
->name
, extension_release_meta
);
634 TAKE_PTR(extension_release_meta
);
638 strv_sort(valid_prefixes
);
641 *ret_image
= TAKE_PTR(image
);
642 if (ret_extension_images
)
643 *ret_extension_images
= TAKE_PTR(extension_images
);
644 if (ret_extension_releases
)
645 *ret_extension_releases
= TAKE_PTR(extension_releases
);
647 *ret_os_release
= TAKE_PTR(os_release
);
649 *ret_unit_files
= TAKE_PTR(unit_files
);
650 if (ret_valid_prefixes
)
651 *ret_valid_prefixes
= TAKE_PTR(valid_prefixes
);
656 int portable_extract(
657 const char *name_or_path
,
659 char **extension_image_paths
,
661 PortableMetadata
**ret_os_release
,
662 OrderedHashmap
**ret_extension_releases
,
663 Hashmap
**ret_unit_files
,
664 char ***ret_valid_prefixes
,
665 sd_bus_error
*error
) {
667 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
668 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
, *extension_releases
= NULL
;
669 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
670 _cleanup_(strv_freep
) char **valid_prefixes
= NULL
;
671 _cleanup_(image_unrefp
) Image
*image
= NULL
;
674 assert(name_or_path
);
676 r
= extract_image_and_extensions(
679 extension_image_paths
,
680 /* validate_sysext= */ false,
681 /* relax_extension_release_check= */ FLAGS_SET(flags
, PORTABLE_FORCE_SYSEXT
),
687 ret_valid_prefixes
? &valid_prefixes
: NULL
,
692 if (hashmap_isempty(unit_files
)) {
693 _cleanup_free_
char *extensions
= strv_join(extension_image_paths
, ", ");
697 return sd_bus_error_setf(error
,
698 SD_BUS_ERROR_INVALID_ARGS
,
699 "Couldn't find any matching unit files in image '%s%s%s', refusing.",
701 isempty(extensions
) ? "" : "' or any of its extensions '",
702 isempty(extensions
) ? "" : extensions
);
706 *ret_os_release
= TAKE_PTR(os_release
);
707 if (ret_extension_releases
)
708 *ret_extension_releases
= TAKE_PTR(extension_releases
);
710 *ret_unit_files
= TAKE_PTR(unit_files
);
711 if (ret_valid_prefixes
)
712 *ret_valid_prefixes
= TAKE_PTR(valid_prefixes
);
717 static int unit_file_is_active(
720 sd_bus_error
*error
) {
722 static const char *const active_states
[] = {
734 /* If we are looking at a plain or instance things are easy, we can just query the state */
735 if (unit_name_is_valid(name
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
)) {
736 _cleanup_free_
char *path
= NULL
, *buf
= NULL
;
738 path
= unit_dbus_path_from_name(name
);
742 r
= sd_bus_get_property_string(
744 "org.freedesktop.systemd1",
746 "org.freedesktop.systemd1.Unit",
751 return log_debug_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(error
, r
));
753 return strv_contains((char**) active_states
, buf
);
756 /* Otherwise we need to enumerate. But let's build the most restricted query we can */
757 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
758 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
759 const char *at
, *prefix
, *joined
;
761 r
= sd_bus_message_new_method_call(
764 "org.freedesktop.systemd1",
765 "/org/freedesktop/systemd1",
766 "org.freedesktop.systemd1.Manager",
767 "ListUnitsByPatterns");
771 r
= sd_bus_message_append_strv(m
, (char**) active_states
);
775 at
= strchr(name
, '@');
778 prefix
= strndupa_safe(name
, at
+ 1 - name
);
779 joined
= strjoina(prefix
, "*", at
+ 1);
781 r
= sd_bus_message_append_strv(m
, STRV_MAKE(joined
));
785 r
= sd_bus_call(bus
, m
, 0, error
, &reply
);
787 return log_debug_errno(r
, "Failed to list units: %s", bus_error_message(error
, r
));
789 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
793 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_STRUCT
, "ssssssouso");
803 static int portable_changes_add(
804 PortableChange
**changes
,
806 int type_or_errno
, /* PORTABLE_COPY, PORTABLE_SYMLINK, … if positive, or errno if negative */
808 const char *source
) {
810 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
814 assert(!changes
== !n_changes
);
816 if (type_or_errno
>= 0)
817 assert(type_or_errno
< _PORTABLE_CHANGE_TYPE_MAX
);
819 assert(type_or_errno
>= -ERRNO_MAX
);
824 c
= reallocarray(*changes
, *n_changes
+ 1, sizeof(PortableChange
));
843 c
[(*n_changes
)++] = (PortableChange
) {
844 .type_or_errno
= type_or_errno
,
846 .source
= TAKE_PTR(s
),
852 static int portable_changes_add_with_prefix(
853 PortableChange
**changes
,
858 const char *source
) {
860 _cleanup_free_
char *path_buf
= NULL
, *source_buf
= NULL
;
863 assert(!changes
== !n_changes
);
869 path_buf
= path_join(prefix
, path
);
876 source_buf
= path_join(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 append_release_log_fields(
945 const PortableMetadata
*release
,
947 const char *field_name
) {
949 static const char *const field_versions
[_IMAGE_CLASS_MAX
][4]= {
950 [IMAGE_PORTABLE
] = { "IMAGE_VERSION", "VERSION_ID", "BUILD_ID", NULL
},
951 [IMAGE_EXTENSION
] = { "SYSEXT_IMAGE_VERSION", "SYSEXT_VERSION_ID", "SYSEXT_BUILD_ID", NULL
},
953 static const char *const field_ids
[_IMAGE_CLASS_MAX
][3]= {
954 [IMAGE_PORTABLE
] = { "IMAGE_ID", "ID", NULL
},
955 [IMAGE_EXTENSION
] = { "SYSEXT_IMAGE_ID", "SYSEXT_ID", NULL
},
957 _cleanup_strv_free_
char **fields
= NULL
;
958 const char *id
= NULL
, *version
= NULL
;
961 assert(IN_SET(type
, IMAGE_PORTABLE
, IMAGE_EXTENSION
));
962 assert(!strv_isempty((char *const *)field_ids
[type
]));
963 assert(!strv_isempty((char *const *)field_versions
[type
]));
968 return 0; /* Nothing to do. */
970 r
= load_env_file_pairs_fd(release
->fd
, release
->name
, &fields
);
972 return log_debug_errno(r
, "Failed to parse '%s': %m", release
->name
);
974 /* Find an ID first, in order of preference from more specific to less specific: IMAGE_ID -> ID */
975 id
= strv_find_first_field((char *const *)field_ids
[type
], fields
);
977 /* Then the version, same logic, prefer the more specific one */
978 version
= strv_find_first_field((char *const *)field_versions
[type
], fields
);
980 /* If there's no valid version to be found, simply omit it. */
989 id
&& version
? "_" : "",
997 static int install_chroot_dropin(
998 const char *image_path
,
1000 OrderedHashmap
*extension_images
,
1001 OrderedHashmap
*extension_releases
,
1002 const PortableMetadata
*m
,
1003 const PortableMetadata
*os_release
,
1004 const char *dropin_dir
,
1005 PortableFlags flags
,
1007 PortableChange
**changes
,
1008 size_t *n_changes
) {
1010 _cleanup_free_
char *text
= NULL
, *dropin
= NULL
;
1017 dropin
= path_join(dropin_dir
, "20-portable.conf");
1021 r
= make_marker_text(image_path
, extension_images
, &text
);
1023 return log_debug_errno(r
, "Failed to generate marker string for portable drop-in: %m");
1025 if (endswith(m
->name
, ".service")) {
1026 const char *os_release_source
, *root_type
;
1027 _cleanup_free_
char *base_name
= NULL
;
1030 root_type
= root_setting_from_image(type
);
1032 if (access("/etc/os-release", F_OK
) < 0) {
1033 if (errno
!= ENOENT
)
1034 return log_debug_errno(errno
, "Failed to check if /etc/os-release exists: %m");
1036 os_release_source
= "/usr/lib/os-release";
1038 os_release_source
= "/etc/os-release";
1040 r
= path_extract_filename(m
->image_path
?: image_path
, &base_name
);
1042 return log_debug_errno(r
, "Failed to extract basename from '%s': %m", m
->image_path
?: image_path
);
1044 if (!strextend(&text
,
1047 root_type
, image_path
, "\n"
1048 "Environment=PORTABLE=", base_name
, "\n"
1049 "BindReadOnlyPaths=", os_release_source
, ":/run/host/os-release\n"
1050 "LogExtraFields=PORTABLE=", base_name
, "\n"))
1053 /* If we have a single image then PORTABLE= will point to it, so we add
1054 * PORTABLE_NAME_AND_VERSION= with the os-release fields and we are done. But if we have
1055 * extensions, PORTABLE= will point to the image where the current unit was found in. So we
1056 * also list PORTABLE_ROOT= and PORTABLE_ROOT_NAME_AND_VERSION= for the base image, and
1057 * PORTABLE_EXTENSION= and PORTABLE_EXTENSION_NAME_AND_VERSION= for each extension, so that
1058 * all needed metadata is available. */
1059 if (ordered_hashmap_isempty(extension_images
))
1060 r
= append_release_log_fields(&text
, os_release
, IMAGE_PORTABLE
, "PORTABLE_NAME_AND_VERSION");
1062 _cleanup_free_
char *root_base_name
= NULL
;
1064 r
= path_extract_filename(image_path
, &root_base_name
);
1066 return log_debug_errno(r
, "Failed to extract basename from '%s': %m", image_path
);
1068 if (!strextend(&text
,
1069 "Environment=PORTABLE_ROOT=", root_base_name
, "\n",
1070 "LogExtraFields=PORTABLE_ROOT=", root_base_name
, "\n"))
1073 r
= append_release_log_fields(&text
, os_release
, IMAGE_PORTABLE
, "PORTABLE_ROOT_NAME_AND_VERSION");
1078 if (m
->image_path
&& !path_equal(m
->image_path
, image_path
))
1079 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
1080 _cleanup_free_
char *extension_base_name
= NULL
;
1082 r
= path_extract_filename(ext
->path
, &extension_base_name
);
1084 return log_debug_errno(r
, "Failed to extract basename from '%s': %m", ext
->path
);
1086 if (!strextend(&text
,
1088 extension_setting_from_image(ext
->type
),
1090 /* With --force tell PID1 to avoid enforcing that the image <name> and
1091 * extension-release.<name> have to match. */
1092 !IN_SET(type
, IMAGE_DIRECTORY
, IMAGE_SUBVOLUME
) &&
1093 FLAGS_SET(flags
, PORTABLE_FORCE_SYSEXT
) ?
1094 ":x-systemd.relax-extension-release-check\n" :
1096 /* In PORTABLE= we list the 'main' image name for this unit
1097 * (the image where the unit was extracted from), but we are
1098 * stacking multiple images, so list those too. */
1099 "LogExtraFields=PORTABLE_EXTENSION=", extension_base_name
, "\n"))
1102 /* Look for image/version identifiers in the extension release files. We
1103 * look for all possible IDs, but typically only 1 or 2 will be set, so
1104 * the number of fields added shouldn't be too large. We prefix the DDI
1105 * name to the value, so that we can add the same field multiple times and
1106 * still be able to identify what applies to what. */
1107 r
= append_release_log_fields(&text
,
1108 ordered_hashmap_get(extension_releases
, ext
->name
),
1110 "PORTABLE_EXTENSION_NAME_AND_VERSION");
1116 r
= write_string_file(dropin
, text
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
1118 return log_debug_errno(r
, "Failed to write '%s': %m", dropin
);
1120 (void) portable_changes_add(changes
, n_changes
, PORTABLE_WRITE
, dropin
, NULL
);
1123 *ret_dropin
= TAKE_PTR(dropin
);
1128 static int install_profile_dropin(
1129 const char *image_path
,
1130 const PortableMetadata
*m
,
1131 const char *dropin_dir
,
1132 const char *profile
,
1133 PortableFlags flags
,
1135 PortableChange
**changes
,
1136 size_t *n_changes
) {
1138 _cleanup_free_
char *dropin
= NULL
, *from
= NULL
;
1148 r
= find_portable_profile(profile
, m
->name
, &from
);
1151 return log_debug_errno(errno
, "Profile '%s' is not accessible: %m", profile
);
1153 log_debug_errno(errno
, "Skipping link to profile '%s', as it does not exist: %m", profile
);
1157 dropin
= path_join(dropin_dir
, "10-profile.conf");
1161 if (flags
& PORTABLE_PREFER_COPY
) {
1163 r
= copy_file_atomic(from
, dropin
, 0644, COPY_REFLINK
);
1165 return log_debug_errno(r
, "Failed to copy %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), dropin
);
1167 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, dropin
, from
);
1171 if (symlink(from
, dropin
) < 0)
1172 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), dropin
);
1174 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, dropin
, from
);
1178 *ret_dropin
= TAKE_PTR(dropin
);
1183 static const char *attached_path(const LookupPaths
*paths
, PortableFlags flags
) {
1188 if (flags
& PORTABLE_RUNTIME
)
1189 where
= paths
->runtime_attached
;
1191 where
= paths
->persistent_attached
;
1197 static int attach_unit_file(
1198 const LookupPaths
*paths
,
1199 const char *image_path
,
1201 OrderedHashmap
*extension_images
,
1202 OrderedHashmap
*extension_releases
,
1203 const PortableMetadata
*m
,
1204 const PortableMetadata
*os_release
,
1205 const char *profile
,
1206 PortableFlags flags
,
1207 PortableChange
**changes
,
1208 size_t *n_changes
) {
1210 _cleanup_(unlink_and_freep
) char *chroot_dropin
= NULL
, *profile_dropin
= NULL
;
1211 _cleanup_(rmdir_and_freep
) char *dropin_dir
= NULL
;
1212 _cleanup_free_
char *path
= NULL
;
1219 assert(PORTABLE_METADATA_IS_UNIT(m
));
1221 where
= attached_path(paths
, flags
);
1223 (void) mkdir_parents(where
, 0755);
1224 if (mkdir(where
, 0755) < 0) {
1225 if (errno
!= EEXIST
)
1226 return log_debug_errno(errno
, "Failed to create attach directory %s: %m", where
);
1228 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, where
, NULL
);
1230 path
= path_join(where
, m
->name
);
1234 dropin_dir
= strjoin(path
, ".d");
1238 if (mkdir(dropin_dir
, 0755) < 0) {
1239 if (errno
!= EEXIST
)
1240 return log_debug_errno(errno
, "Failed to create drop-in directory %s: %m", dropin_dir
);
1242 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, dropin_dir
, NULL
);
1244 /* We install the drop-ins first, and the actual unit file last to achieve somewhat atomic behaviour if PID 1
1245 * is reloaded while we are creating things here: as long as only the drop-ins exist the unit doesn't exist at
1248 r
= install_chroot_dropin(image_path
, type
, extension_images
, extension_releases
, m
, os_release
, dropin_dir
, flags
, &chroot_dropin
, changes
, n_changes
);
1252 r
= install_profile_dropin(image_path
, m
, dropin_dir
, profile
, flags
, &profile_dropin
, changes
, n_changes
);
1256 if ((flags
& PORTABLE_PREFER_SYMLINK
) && m
->source
) {
1258 if (symlink(m
->source
, path
) < 0)
1259 return log_debug_errno(errno
, "Failed to symlink unit file '%s': %m", path
);
1261 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, path
, m
->source
);
1264 _cleanup_(unlink_and_freep
) char *tmp
= NULL
;
1265 _cleanup_close_
int fd
= -EBADF
;
1267 (void) mac_selinux_create_file_prepare_label(path
, m
->selinux_label
);
1269 fd
= open_tmpfile_linkable(path
, O_WRONLY
|O_CLOEXEC
, &tmp
);
1270 mac_selinux_create_file_clear(); /* Clear immediately in case of errors */
1272 return log_debug_errno(fd
, "Failed to create unit file '%s': %m", path
);
1274 r
= copy_bytes(m
->fd
, fd
, UINT64_MAX
, COPY_REFLINK
);
1276 return log_debug_errno(r
, "Failed to copy unit file '%s': %m", path
);
1278 if (fchmod(fd
, 0644) < 0)
1279 return log_debug_errno(errno
, "Failed to change unit file access mode for '%s': %m", path
);
1281 r
= link_tmpfile(fd
, tmp
, path
, /* replace= */ false);
1283 return log_debug_errno(r
, "Failed to install unit file '%s': %m", path
);
1287 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, path
, m
->source
);
1290 /* All is established now, now let's disable any rollbacks */
1291 chroot_dropin
= mfree(chroot_dropin
);
1292 profile_dropin
= mfree(profile_dropin
);
1293 dropin_dir
= mfree(dropin_dir
);
1298 static int image_symlink(
1299 const char *image_path
,
1300 PortableFlags flags
,
1303 const char *fn
, *where
;
1304 char *joined
= NULL
;
1309 fn
= last_path_component(image_path
);
1311 if (flags
& PORTABLE_RUNTIME
)
1312 where
= "/run/portables/";
1314 where
= "/etc/portables/";
1316 joined
= strjoin(where
, fn
);
1324 static int install_image_symlink(
1325 const char *image_path
,
1326 PortableFlags flags
,
1327 PortableChange
**changes
,
1328 size_t *n_changes
) {
1330 _cleanup_free_
char *sl
= NULL
;
1335 /* If the image is outside of the image search also link it into it, so that it can be found with short image
1336 * names and is listed among the images. */
1338 if (image_in_search_path(IMAGE_PORTABLE
, NULL
, image_path
))
1341 r
= image_symlink(image_path
, flags
, &sl
);
1343 return log_debug_errno(r
, "Failed to generate image symlink path: %m");
1345 (void) mkdir_parents(sl
, 0755);
1347 if (symlink(image_path
, sl
) < 0)
1348 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", image_path
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), sl
);
1350 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, sl
, image_path
);
1354 static int install_image_and_extensions_symlinks(
1356 OrderedHashmap
*extension_images
,
1357 PortableFlags flags
,
1358 PortableChange
**changes
,
1359 size_t *n_changes
) {
1366 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
1367 r
= install_image_symlink(ext
->path
, flags
, changes
, n_changes
);
1372 r
= install_image_symlink(image
->path
, flags
, changes
, n_changes
);
1379 static bool prefix_matches_compatible(char **matches
, char **valid_prefixes
) {
1380 /* Checks if all 'matches' are included in the list of 'valid_prefixes' */
1382 STRV_FOREACH(m
, matches
)
1383 if (!strv_contains(valid_prefixes
, *m
))
1389 int portable_attach(
1391 const char *name_or_path
,
1393 const char *profile
,
1394 char **extension_image_paths
,
1395 PortableFlags flags
,
1396 PortableChange
**changes
,
1398 sd_bus_error
*error
) {
1400 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
, *extension_releases
= NULL
;
1401 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
1402 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
1403 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1404 _cleanup_strv_free_
char **valid_prefixes
= NULL
;
1405 _cleanup_(image_unrefp
) Image
*image
= NULL
;
1406 PortableMetadata
*item
;
1409 r
= extract_image_and_extensions(
1412 extension_image_paths
,
1413 /* validate_sysext= */ true,
1414 /* relax_extension_release_check= */ FLAGS_SET(flags
, PORTABLE_FORCE_SYSEXT
),
1417 &extension_releases
,
1425 if (valid_prefixes
&& !prefix_matches_compatible(matches
, valid_prefixes
)) {
1426 _cleanup_free_
char *matches_joined
= NULL
, *extensions_joined
= NULL
, *valid_prefixes_joined
= NULL
;
1428 matches_joined
= strv_join(matches
, "', '");
1429 if (!matches_joined
)
1432 extensions_joined
= strv_join(extension_image_paths
, ", ");
1433 if (!extensions_joined
)
1436 valid_prefixes_joined
= strv_join(valid_prefixes
, ", ");
1437 if (!valid_prefixes_joined
)
1440 return sd_bus_error_setf(
1442 SD_BUS_ERROR_INVALID_ARGS
,
1443 "Selected matches '%s' are not compatible with portable service image '%s%s%s', refusing. (Acceptable prefix matches are: %s)",
1446 isempty(extensions_joined
) ? "" : "' or any of its extensions '",
1447 strempty(extensions_joined
),
1448 valid_prefixes_joined
);
1451 if (hashmap_isempty(unit_files
)) {
1452 _cleanup_free_
char *extensions_joined
= strv_join(extension_image_paths
, ", ");
1453 if (!extensions_joined
)
1456 return sd_bus_error_setf(
1458 SD_BUS_ERROR_INVALID_ARGS
,
1459 "Couldn't find any matching unit files in image '%s%s%s', refusing.",
1461 isempty(extensions_joined
) ? "" : "' or any of its extensions '",
1462 strempty(extensions_joined
));
1465 r
= lookup_paths_init(&paths
, RUNTIME_SCOPE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1469 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && !FLAGS_SET(flags
, PORTABLE_FORCE_ATTACH
))
1470 HASHMAP_FOREACH(item
, unit_files
) {
1471 r
= unit_file_exists(RUNTIME_SCOPE_SYSTEM
, &paths
, item
->name
);
1473 return sd_bus_error_set_errnof(error
, r
, "Failed to determine whether unit '%s' exists on the host: %m", item
->name
);
1475 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' exists on the host already, refusing.", item
->name
);
1477 r
= unit_file_is_active(bus
, item
->name
, error
);
1481 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active already, refusing.", item
->name
);
1484 HASHMAP_FOREACH(item
, unit_files
) {
1485 r
= attach_unit_file(&paths
, image
->path
, image
->type
, extension_images
, extension_releases
,
1486 item
, os_release
, profile
, flags
, changes
, n_changes
);
1488 return sd_bus_error_set_errnof(error
, r
, "Failed to attach unit '%s': %m", item
->name
);
1491 /* We don't care too much for the image symlink, it's just a convenience thing, it's not necessary for proper
1492 * operation otherwise. */
1493 (void) install_image_and_extensions_symlinks(image
, extension_images
, flags
, changes
, n_changes
);
1498 static bool marker_matches_images(const char *marker
, const char *name_or_path
, char **extension_image_paths
) {
1499 _cleanup_strv_free_
char **root_and_extensions
= NULL
;
1504 assert(name_or_path
);
1506 /* If extensions were used when attaching, the marker will be a colon-separated
1507 * list of images/paths. We enforce strict 1:1 matching, so that we are sure
1508 * we are detaching exactly what was attached.
1509 * For each image, starting with the root, we look for a token in the marker,
1510 * and return a negative answer on any non-matching combination. */
1512 root_and_extensions
= strv_new(name_or_path
);
1513 if (!root_and_extensions
)
1516 r
= strv_extend_strv(&root_and_extensions
, extension_image_paths
, false);
1520 STRV_FOREACH(image_name_or_path
, root_and_extensions
) {
1521 _cleanup_free_
char *image
= NULL
;
1523 r
= extract_first_word(&marker
, &image
, ":", EXTRACT_UNQUOTE
|EXTRACT_RETAIN_ESCAPE
);
1525 return log_debug_errno(r
, "Failed to parse marker: %s", marker
);
1529 a
= last_path_component(image
);
1531 if (image_name_is_valid(*image_name_or_path
)) {
1532 const char *e
, *underscore
;
1534 /* We shall match against an image name. In that case let's compare the last component, and optionally
1535 * allow either a suffix of ".raw" or a series of "/".
1536 * But allow matching on a different version of the same image, when a "_" is used as a separator. */
1537 underscore
= strchr(*image_name_or_path
, '_');
1539 if (strneq(a
, *image_name_or_path
, underscore
- *image_name_or_path
))
1544 e
= startswith(a
, *image_name_or_path
);
1548 if(!(e
[strspn(e
, "/")] == 0 || streq(e
, ".raw")))
1551 const char *b
, *underscore
;
1554 /* We shall match against a path. Let's ignore any prefix here though, as often there are many ways to
1555 * reach the same file. However, in this mode, let's validate any file suffix.
1556 * But also ensure that we don't fail if both components don't have a '/' at all
1557 * (strcspn returns the full length of the string in that case, which might not
1558 * match as the versions might differ). */
1560 l
= strcspn(a
, "/");
1561 b
= last_path_component(*image_name_or_path
);
1563 if ((a
[l
] != '/') != !strchr(b
, '/')) /* One is a directory, the other is not */
1566 if (a
[l
] != 0 && strcspn(b
, "/") != l
)
1569 underscore
= strchr(b
, '_');
1572 else { /* Either component could be versioned */
1573 underscore
= strchr(a
, '_');
1578 if (!strneq(a
, b
, l
))
1586 static int test_chroot_dropin(
1590 const char *name_or_path
,
1591 char **extension_image_paths
,
1592 char **ret_marker
) {
1594 _cleanup_free_
char *line
= NULL
, *marker
= NULL
;
1595 _cleanup_fclose_
FILE *f
= NULL
;
1596 _cleanup_close_
int fd
= -EBADF
;
1597 const char *p
, *e
, *k
;
1604 /* We recognize unis created from portable images via the drop-in we created for them */
1606 p
= strjoina(fname
, ".d/20-portable.conf");
1607 fd
= openat(dirfd(d
), p
, O_RDONLY
|O_CLOEXEC
);
1609 if (errno
== ENOENT
)
1612 return log_debug_errno(errno
, "Failed to open %s/%s: %m", where
, p
);
1615 r
= take_fdopen_unlocked(&fd
, "r", &f
);
1617 return log_debug_errno(r
, "Failed to convert file handle: %m");
1619 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1621 return log_debug_errno(r
, "Failed to read from %s/%s: %m", where
, p
);
1623 e
= startswith(line
, PORTABLE_DROPIN_MARKER_BEGIN
);
1627 k
= endswith(e
, PORTABLE_DROPIN_MARKER_END
);
1631 marker
= strndup(e
, k
- e
);
1638 r
= marker_matches_images(marker
, name_or_path
, extension_image_paths
);
1641 *ret_marker
= TAKE_PTR(marker
);
1646 int portable_detach(
1648 const char *name_or_path
,
1649 char **extension_image_paths
,
1650 PortableFlags flags
,
1651 PortableChange
**changes
,
1653 sd_bus_error
*error
) {
1655 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1656 _cleanup_set_free_ Set
*unit_files
= NULL
, *markers
= NULL
;
1657 _cleanup_free_
char *extensions
= NULL
;
1658 _cleanup_closedir_
DIR *d
= NULL
;
1659 const char *where
, *item
;
1663 assert(name_or_path
);
1665 r
= lookup_paths_init(&paths
, RUNTIME_SCOPE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1669 where
= attached_path(&paths
, flags
);
1673 if (errno
== ENOENT
)
1676 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1679 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1680 _cleanup_free_
char *marker
= NULL
, *unit_name
= NULL
;
1683 /* When a portable service is enabled with "portablectl --copy=symlink --enable --now attach",
1684 * and is disabled with "portablectl --enable --now detach", which calls DisableUnitFilesWithFlags
1685 * DBus method, the main unit file is removed, but its drop-ins are not. Hence, here we need
1686 * to list both main unit files and drop-in directories (without the main unit files). */
1688 dot
= endswith(de
->d_name
, ".d");
1690 unit_name
= strndup(de
->d_name
, dot
- de
->d_name
);
1692 unit_name
= strdup(de
->d_name
);
1696 if (!unit_name_is_valid(unit_name
, UNIT_NAME_ANY
))
1699 /* Filter out duplicates */
1700 if (set_contains(unit_files
, unit_name
))
1703 if (dot
? !IN_SET(de
->d_type
, DT_LNK
, DT_DIR
) : !IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1706 r
= test_chroot_dropin(d
, where
, unit_name
, name_or_path
, extension_image_paths
, &marker
);
1712 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && !FLAGS_SET(flags
, PORTABLE_FORCE_ATTACH
)) {
1713 r
= unit_file_is_active(bus
, unit_name
, error
);
1717 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active, can't detach.", unit_name
);
1720 r
= set_ensure_consume(&unit_files
, &string_hash_ops_free
, TAKE_PTR(unit_name
));
1722 return log_oom_debug();
1724 for (const char *p
= marker
;;) {
1725 _cleanup_free_
char *image
= NULL
;
1727 r
= extract_first_word(&p
, &image
, ":", EXTRACT_UNESCAPE_SEPARATORS
|EXTRACT_RETAIN_ESCAPE
);
1729 return log_debug_errno(r
, "Failed to parse marker: %s", p
);
1733 if (path_is_absolute(image
) && !image_in_search_path(IMAGE_PORTABLE
, NULL
, image
)) {
1734 r
= set_ensure_consume(&markers
, &path_hash_ops_free
, TAKE_PTR(image
));
1741 if (set_isempty(unit_files
))
1744 SET_FOREACH(item
, unit_files
) {
1745 _cleanup_free_
char *md
= NULL
;
1747 if (unlinkat(dirfd(d
), item
, 0) < 0) {
1748 log_debug_errno(errno
, "Can't remove unit file %s/%s: %m", where
, item
);
1750 if (errno
!= ENOENT
&& ret
>= 0)
1753 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, item
, NULL
);
1755 FOREACH_STRING(suffix
, ".d/10-profile.conf", ".d/20-portable.conf") {
1756 _cleanup_free_
char *dropin
= NULL
;
1758 dropin
= strjoin(item
, suffix
);
1762 if (unlinkat(dirfd(d
), dropin
, 0) < 0) {
1763 log_debug_errno(errno
, "Can't remove drop-in %s/%s: %m", where
, dropin
);
1765 if (errno
!= ENOENT
&& ret
>= 0)
1768 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, dropin
, NULL
);
1771 md
= strjoin(item
, ".d");
1775 if (unlinkat(dirfd(d
), md
, AT_REMOVEDIR
) < 0) {
1776 log_debug_errno(errno
, "Can't remove drop-in directory %s/%s: %m", where
, md
);
1778 if (errno
!= ENOENT
&& ret
>= 0)
1781 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, md
, NULL
);
1784 /* Now, also drop any image symlink, for images outside of the sarch path */
1785 SET_FOREACH(item
, markers
) {
1786 _cleanup_free_
char *sl
= NULL
;
1789 r
= image_symlink(item
, flags
, &sl
);
1791 log_debug_errno(r
, "Failed to determine image symlink for '%s', ignoring: %m", item
);
1795 if (lstat(sl
, &st
) < 0) {
1796 log_debug_errno(errno
, "Failed to stat '%s', ignoring: %m", sl
);
1800 if (!S_ISLNK(st
.st_mode
)) {
1801 log_debug("Image '%s' is not a symlink, ignoring.", sl
);
1805 if (unlink(sl
) < 0) {
1806 log_debug_errno(errno
, "Can't remove image symlink '%s': %m", sl
);
1808 if (errno
!= ENOENT
&& ret
>= 0)
1811 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, sl
, NULL
);
1814 /* Try to remove the unit file directory, if we can */
1815 if (rmdir(where
) >= 0)
1816 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, where
, NULL
);
1821 extensions
= strv_join(extension_image_paths
, ", ");
1825 r
= sd_bus_error_setf(error
,
1826 BUS_ERROR_NO_SUCH_UNIT
,
1827 "No unit files associated with '%s%s%s' found attached to the system. Image not attached?",
1829 isempty(extensions
) ? "" : "' or any of its extensions '",
1830 isempty(extensions
) ? "" : extensions
);
1831 return log_debug_errno(r
, "%s", error
->message
);
1834 static int portable_get_state_internal(
1836 const char *name_or_path
,
1837 char **extension_image_paths
,
1838 PortableFlags flags
,
1840 sd_bus_error
*error
) {
1842 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1843 bool found_enabled
= false, found_running
= false;
1844 _cleanup_set_free_ Set
*unit_files
= NULL
;
1845 _cleanup_closedir_
DIR *d
= NULL
;
1849 assert(name_or_path
);
1852 r
= lookup_paths_init(&paths
, RUNTIME_SCOPE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1856 where
= attached_path(&paths
, flags
);
1860 if (errno
== ENOENT
) {
1861 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1862 *ret
= PORTABLE_DETACHED
;
1866 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1869 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1870 UnitFileState state
;
1872 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1875 /* Filter out duplicates */
1876 if (set_contains(unit_files
, de
->d_name
))
1879 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1882 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, extension_image_paths
, NULL
);
1888 r
= unit_file_lookup_state(RUNTIME_SCOPE_SYSTEM
, &paths
, de
->d_name
, &state
);
1890 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1891 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_LINKED_RUNTIME
))
1892 found_enabled
= true;
1894 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1898 found_running
= true;
1900 r
= set_put_strdup(&unit_files
, de
->d_name
);
1902 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1905 *ret
= found_running
? (!set_isempty(unit_files
) && (flags
& PORTABLE_RUNTIME
) ? PORTABLE_RUNNING_RUNTIME
: PORTABLE_RUNNING
) :
1906 found_enabled
? (flags
& PORTABLE_RUNTIME
? PORTABLE_ENABLED_RUNTIME
: PORTABLE_ENABLED
) :
1907 !set_isempty(unit_files
) ? (flags
& PORTABLE_RUNTIME
? PORTABLE_ATTACHED_RUNTIME
: PORTABLE_ATTACHED
) : PORTABLE_DETACHED
;
1912 int portable_get_state(
1914 const char *name_or_path
,
1915 char **extension_image_paths
,
1916 PortableFlags flags
,
1918 sd_bus_error
*error
) {
1920 PortableState state
;
1923 assert(name_or_path
);
1926 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1927 * the latter only if we didn't find anything in the former. */
1929 r
= portable_get_state_internal(bus
, name_or_path
, extension_image_paths
, flags
& ~PORTABLE_RUNTIME
, &state
, error
);
1933 if (state
== PORTABLE_DETACHED
) {
1934 r
= portable_get_state_internal(bus
, name_or_path
, extension_image_paths
, flags
| PORTABLE_RUNTIME
, &state
, error
);
1943 int portable_get_profiles(char ***ret
) {
1946 return conf_files_list_nulstr(ret
, NULL
, NULL
, CONF_FILES_DIRECTORY
|CONF_FILES_BASENAME
|CONF_FILES_FILTER_MASKED
, PORTABLE_PROFILE_DIRS
);
1949 static const char* const portable_change_type_table
[_PORTABLE_CHANGE_TYPE_MAX
] = {
1950 [PORTABLE_COPY
] = "copy",
1951 [PORTABLE_MKDIR
] = "mkdir",
1952 [PORTABLE_SYMLINK
] = "symlink",
1953 [PORTABLE_UNLINK
] = "unlink",
1954 [PORTABLE_WRITE
] = "write",
1957 DEFINE_STRING_TABLE_LOOKUP(portable_change_type
, int);
1959 static const char* const portable_state_table
[_PORTABLE_STATE_MAX
] = {
1960 [PORTABLE_DETACHED
] = "detached",
1961 [PORTABLE_ATTACHED
] = "attached",
1962 [PORTABLE_ATTACHED_RUNTIME
] = "attached-runtime",
1963 [PORTABLE_ENABLED
] = "enabled",
1964 [PORTABLE_ENABLED_RUNTIME
] = "enabled-runtime",
1965 [PORTABLE_RUNNING
] = "running",
1966 [PORTABLE_RUNNING_RUNTIME
] = "running-runtime",
1969 DEFINE_STRING_TABLE_LOOKUP(portable_state
, PortableState
);