1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <linux/loop.h>
5 #include "bus-common-errors.h"
7 #include "conf-files.h"
9 #include "data-fd-util.h"
11 #include "dirent-util.h"
12 #include "discover-image.h"
13 #include "dissect-image.h"
14 #include "errno-list.h"
21 #include "locale-util.h"
22 #include "loop-util.h"
24 #include "nulstr-util.h"
26 #include "path-lookup.h"
28 #include "process-util.h"
30 #include "signal-util.h"
31 #include "socket-util.h"
32 #include "sort-util.h"
33 #include "string-table.h"
35 #include "tmpfile-util.h"
36 #include "user-util.h"
38 static const char profile_dirs
[] = CONF_PATHS_NULSTR("systemd/portable/profile");
40 /* Markers used in the first line of our 20-portable.conf unit file drop-in to determine, that a) the unit file was
41 * dropped there by the portable service logic and b) for which image it was dropped there. */
42 #define PORTABLE_DROPIN_MARKER_BEGIN "# Drop-in created for image '"
43 #define PORTABLE_DROPIN_MARKER_END "', do not edit."
45 static bool prefix_match(const char *unit
, const char *prefix
) {
48 p
= startswith(unit
, prefix
);
52 /* Only respect prefixes followed by dash or dot or when there's a complete match */
53 return IN_SET(*p
, '-', '.', '@', 0);
56 static bool unit_match(const char *unit
, char **matches
) {
60 dot
= strrchr(unit
, '.');
64 if (!STR_IN_SET(dot
, ".service", ".socket", ".target", ".timer", ".path"))
67 /* Empty match expression means: everything */
68 if (strv_isempty(matches
))
71 /* Otherwise, at least one needs to match */
72 STRV_FOREACH(i
, matches
)
73 if (prefix_match(unit
, *i
))
79 static PortableMetadata
*portable_metadata_new(const char *name
, const char *path
, int fd
) {
82 m
= malloc0(offsetof(PortableMetadata
, name
) + strlen(name
) + 1);
86 /* In case of a layered attach, we want to remember which image the unit came from */
88 m
->image_path
= strdup(path
);
93 strcpy(m
->name
, name
);
99 PortableMetadata
*portable_metadata_unref(PortableMetadata
*i
) {
110 static int compare_metadata(PortableMetadata
*const *x
, PortableMetadata
*const *y
) {
111 return strcmp((*x
)->name
, (*y
)->name
);
114 int portable_metadata_hashmap_to_sorted_array(Hashmap
*unit_files
, PortableMetadata
***ret
) {
116 _cleanup_free_ PortableMetadata
**sorted
= NULL
;
117 PortableMetadata
*item
;
120 sorted
= new(PortableMetadata
*, hashmap_size(unit_files
));
124 HASHMAP_FOREACH(item
, unit_files
)
127 assert(k
== hashmap_size(unit_files
));
129 typesafe_qsort(sorted
, k
, compare_metadata
);
131 *ret
= TAKE_PTR(sorted
);
135 static int send_item(
140 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
= {};
143 .msg_control
= &control
,
144 .msg_controllen
= sizeof(control
),
148 struct cmsghdr
*cmsg
;
149 _cleanup_close_
int data_fd
= -1;
151 assert(socket_fd
>= 0);
155 data_fd
= copy_data_fd(fd
);
159 cmsg
= CMSG_FIRSTHDR(&mh
);
160 cmsg
->cmsg_level
= SOL_SOCKET
;
161 cmsg
->cmsg_type
= SCM_RIGHTS
;
162 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
163 memcpy(CMSG_DATA(cmsg
), &data_fd
, sizeof(int));
165 iovec
= IOVEC_MAKE_STRING(name
);
167 if (sendmsg(socket_fd
, &mh
, MSG_NOSIGNAL
) < 0)
173 static int recv_item(
178 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
;
179 char buffer
[PATH_MAX
+2];
180 struct iovec iov
= IOVEC_INIT(buffer
, sizeof(buffer
)-1);
182 .msg_control
= &control
,
183 .msg_controllen
= sizeof(control
),
187 struct cmsghdr
*cmsg
;
188 _cleanup_close_
int found_fd
= -1;
192 assert(socket_fd
>= 0);
196 n
= recvmsg_safe(socket_fd
, &mh
, MSG_CMSG_CLOEXEC
);
200 CMSG_FOREACH(cmsg
, &mh
) {
201 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
202 cmsg
->cmsg_type
== SCM_RIGHTS
) {
204 if (cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
205 assert(found_fd
< 0);
206 found_fd
= *(int*) CMSG_DATA(cmsg
);
217 copy
= strdup(buffer
);
222 *ret_fd
= TAKE_FD(found_fd
);
227 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(portable_metadata_hash_ops
, char, string_hash_func
, string_compare_func
,
228 PortableMetadata
, portable_metadata_unref
);
230 static int extract_now(
234 PortableMetadata
**ret_os_release
,
235 Hashmap
**ret_unit_files
) {
237 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
238 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
239 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
240 _cleanup_close_
int os_release_fd
= -1;
241 _cleanup_free_
char *os_release_path
= NULL
;
245 /* Extracts the metadata from a directory tree 'where'. Extracts two kinds of information: the /etc/os-release
246 * data, and all unit files matching the specified expression. Note that this function is called in two very
247 * different but also similar contexts. When the tool gets invoked on a directory tree, we'll process it
248 * directly, and in-process, and thus can return the requested data directly, via 'ret_os_release' and
249 * 'ret_unit_files'. However, if the tool is invoked on a raw disk image — which needs to be mounted first — we
250 * are invoked in a child process with private mounts and then need to send the collected data to our
251 * parent. To handle both cases in one call this function also gets a 'socket_fd' parameter, which when >= 0 is
252 * used to send the data to the parent. */
256 /* First, find /etc/os-release and send it upstream (or just save it). */
257 r
= open_os_release(where
, &os_release_path
, &os_release_fd
);
259 log_debug_errno(r
, "Couldn't acquire os-release file, ignoring: %m");
261 if (socket_fd
>= 0) {
262 r
= send_item(socket_fd
, "/etc/os-release", os_release_fd
);
264 return log_debug_errno(r
, "Failed to send os-release file: %m");
267 if (ret_os_release
) {
268 os_release
= portable_metadata_new("/etc/os-release", NULL
, os_release_fd
);
273 os_release
->source
= TAKE_PTR(os_release_path
);
277 /* Then, send unit file data to the parent (or/and add it to the hashmap). For that we use our usual unit
278 * discovery logic. Note that we force looking inside of /lib/systemd/system/ for units too, as we mightbe
279 * compiled for a split-usr system but the image might be a legacy-usr one. */
280 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, where
);
282 return log_debug_errno(r
, "Failed to acquire lookup paths: %m");
284 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
288 STRV_FOREACH(i
, paths
.search_path
) {
289 _cleanup_free_
char *resolved
= NULL
;
290 _cleanup_closedir_
DIR *d
= NULL
;
293 r
= chase_symlinks_and_opendir(*i
, where
, 0, &resolved
, &d
);
295 log_debug_errno(r
, "Failed to open unit path '%s', ignoring: %m", *i
);
299 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to read directory: %m")) {
300 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*m
= NULL
;
301 _cleanup_close_
int fd
= -1;
303 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
306 if (!unit_match(de
->d_name
, matches
))
309 /* Filter out duplicates */
310 if (hashmap_get(unit_files
, de
->d_name
))
313 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
316 fd
= openat(dirfd(d
), de
->d_name
, O_CLOEXEC
|O_RDONLY
);
318 log_debug_errno(errno
, "Failed to open unit file '%s', ignoring: %m", de
->d_name
);
322 if (socket_fd
>= 0) {
323 r
= send_item(socket_fd
, de
->d_name
, fd
);
325 return log_debug_errno(r
, "Failed to send unit metadata to parent: %m");
328 m
= portable_metadata_new(de
->d_name
, NULL
, fd
);
333 m
->source
= path_join(resolved
, de
->d_name
);
337 r
= hashmap_put(unit_files
, m
->name
, m
);
339 return log_debug_errno(r
, "Failed to add unit to hashmap: %m");
345 *ret_os_release
= TAKE_PTR(os_release
);
347 *ret_unit_files
= TAKE_PTR(unit_files
);
352 static int portable_extract_by_path(
354 bool extract_os_release
,
356 PortableMetadata
**ret_os_release
,
357 Hashmap
**ret_unit_files
,
358 sd_bus_error
*error
) {
360 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
361 _cleanup_(portable_metadata_unrefp
) PortableMetadata
* os_release
= NULL
;
362 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
367 r
= loop_device_make_by_path(path
, O_RDONLY
, LO_FLAGS_PARTSCAN
, &d
);
369 /* We can't turn this into a loop-back block device, and this returns EISDIR? Then this is a directory
370 * tree and not a raw device. It's easy then. */
372 r
= extract_now(path
, matches
, -1, &os_release
, &unit_files
);
377 return log_debug_errno(r
, "Failed to set up loopback device for %s: %m", path
);
379 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
380 _cleanup_(rmdir_and_freep
) char *tmpdir
= NULL
;
381 _cleanup_(close_pairp
) int seq
[2] = { -1, -1 };
382 _cleanup_(sigkill_waitp
) pid_t child
= 0;
384 /* We now have a loopback block device, let's fork off a child in its own mount namespace, mount it
385 * there, and extract the metadata we need. The metadata is sent from the child back to us. */
387 BLOCK_SIGNALS(SIGCHLD
);
389 r
= mkdtemp_malloc("/tmp/inspect-XXXXXX", &tmpdir
);
391 return log_debug_errno(r
, "Failed to create temporary directory: %m");
397 d
->uevent_seqnum_not_before
,
398 d
->timestamp_not_before
,
399 DISSECT_IMAGE_READ_ONLY
|
400 DISSECT_IMAGE_GENERIC_ROOT
|
401 DISSECT_IMAGE_REQUIRE_ROOT
|
402 DISSECT_IMAGE_DISCARD_ON_LOOP
|
403 DISSECT_IMAGE_RELAX_VAR_CHECK
|
404 DISSECT_IMAGE_USR_NO_ROOT
,
407 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't identify a suitable partition table or file system in '%s'.", path
);
408 else if (r
== -EADDRNOTAVAIL
)
409 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No root partition for specified root hash found in '%s'.", path
);
410 else if (r
== -ENOTUNIQ
)
411 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Multiple suitable root partitions found in image '%s'.", path
);
412 else if (r
== -ENXIO
)
413 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No suitable root partition found in image '%s'.", path
);
414 else if (r
== -EPROTONOSUPPORT
)
415 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
);
419 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, seq
) < 0)
420 return log_debug_errno(errno
, "Failed to allocated SOCK_SEQPACKET socket: %m");
422 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
|FORK_LOG
, &child
);
426 seq
[0] = safe_close(seq
[0]);
428 r
= dissected_image_mount(m
, tmpdir
, UID_INVALID
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
);
430 log_debug_errno(r
, "Failed to mount dissected image: %m");
434 r
= extract_now(tmpdir
, matches
, seq
[1], NULL
, NULL
);
437 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
440 seq
[1] = safe_close(seq
[1]);
442 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
447 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*add
= NULL
;
448 _cleanup_free_
char *name
= NULL
;
449 _cleanup_close_
int fd
= -1;
451 r
= recv_item(seq
[0], &name
, &fd
);
453 return log_debug_errno(r
, "Failed to receive item: %m");
455 /* We can't really distinguish a zero-length datagram without any fds from EOF (both are signalled the
456 * same way by recvmsg()). Hence, accept either as end notification. */
457 if (isempty(name
) && fd
< 0)
460 if (isempty(name
) || fd
< 0)
461 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
462 "Invalid item sent from child.");
464 add
= portable_metadata_new(name
, path
, fd
);
469 /* Note that we do not initialize 'add->source' here, as the source path is not usable here as
470 * it refers to a path only valid in the short-living namespaced child process we forked
473 if (PORTABLE_METADATA_IS_UNIT(add
)) {
474 r
= hashmap_put(unit_files
, add
->name
, add
);
476 return log_debug_errno(r
, "Failed to add item to unit file list: %m");
480 } else if (PORTABLE_METADATA_IS_OS_RELEASE(add
)) {
483 os_release
= TAKE_PTR(add
);
485 assert_not_reached();
488 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
494 /* When the portable image is layered, the image with units will not
495 * have a full filesystem, so no os-release - it will be in the root layer */
496 if (extract_os_release
&& !os_release
)
497 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Image '%s' lacks os-release data, refusing.", path
);
499 if (!extract_os_release
&& hashmap_isempty(unit_files
))
500 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't find any matching unit files in image '%s', refusing.", path
);
503 *ret_unit_files
= TAKE_PTR(unit_files
);
506 *ret_os_release
= TAKE_PTR(os_release
);
511 int portable_extract(
512 const char *name_or_path
,
514 char **extension_image_paths
,
515 PortableMetadata
**ret_os_release
,
516 Hashmap
**ret_unit_files
,
517 sd_bus_error
*error
) {
519 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
520 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
;
521 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
522 _cleanup_(image_unrefp
) Image
*image
= NULL
;
526 assert(name_or_path
);
528 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, NULL
, &image
);
532 if (!strv_isempty(extension_image_paths
)) {
535 extension_images
= ordered_hashmap_new(&image_hash_ops
);
536 if (!extension_images
)
539 STRV_FOREACH(p
, extension_image_paths
) {
540 _cleanup_(image_unrefp
) Image
*new = NULL
;
542 r
= image_find_harder(IMAGE_PORTABLE
, *p
, NULL
, &new);
546 r
= ordered_hashmap_put(extension_images
, new->name
, new);
553 r
= portable_extract_by_path(image
->path
, true, matches
, &os_release
, &unit_files
, error
);
557 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
558 _cleanup_hashmap_free_ Hashmap
*extra_unit_files
= NULL
;
560 r
= portable_extract_by_path(ext
->path
, false, matches
, NULL
, &extra_unit_files
, error
);
563 r
= hashmap_move(unit_files
, extra_unit_files
);
568 *ret_os_release
= TAKE_PTR(os_release
);
569 *ret_unit_files
= TAKE_PTR(unit_files
);
574 static int unit_file_is_active(
577 sd_bus_error
*error
) {
579 static const char *const active_states
[] = {
591 /* If we are looking at a plain or instance things are easy, we can just query the state */
592 if (unit_name_is_valid(name
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
)) {
593 _cleanup_free_
char *path
= NULL
, *buf
= NULL
;
595 path
= unit_dbus_path_from_name(name
);
599 r
= sd_bus_get_property_string(
601 "org.freedesktop.systemd1",
603 "org.freedesktop.systemd1.Unit",
608 return log_debug_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(error
, r
));
610 return strv_contains((char**) active_states
, buf
);
613 /* Otherwise we need to enumerate. But let's build the most restricted query we can */
614 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
615 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
616 const char *at
, *prefix
, *joined
;
618 r
= sd_bus_message_new_method_call(
621 "org.freedesktop.systemd1",
622 "/org/freedesktop/systemd1",
623 "org.freedesktop.systemd1.Manager",
624 "ListUnitsByPatterns");
628 r
= sd_bus_message_append_strv(m
, (char**) active_states
);
632 at
= strchr(name
, '@');
635 prefix
= strndupa(name
, at
+ 1 - name
);
636 joined
= strjoina(prefix
, "*", at
+ 1);
638 r
= sd_bus_message_append_strv(m
, STRV_MAKE(joined
));
642 r
= sd_bus_call(bus
, m
, 0, error
, &reply
);
644 return log_debug_errno(r
, "Failed to list units: %s", bus_error_message(error
, r
));
646 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
650 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_STRUCT
, "ssssssouso");
660 static int portable_changes_add(
661 PortableChange
**changes
,
663 int type_or_errno
, /* PORTABLE_COPY, PORTABLE_SYMLINK, … if positive, or errno if negative */
665 const char *source
) {
667 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
671 assert(!changes
== !n_changes
);
673 if (type_or_errno
>= 0)
674 assert(type_or_errno
< _PORTABLE_CHANGE_TYPE_MAX
);
676 assert(type_or_errno
>= -ERRNO_MAX
);
681 c
= reallocarray(*changes
, *n_changes
+ 1, sizeof(PortableChange
));
700 c
[(*n_changes
)++] = (PortableChange
) {
701 .type_or_errno
= type_or_errno
,
703 .source
= TAKE_PTR(s
),
709 static int portable_changes_add_with_prefix(
710 PortableChange
**changes
,
715 const char *source
) {
718 assert(!changes
== !n_changes
);
724 path
= prefix_roota(prefix
, path
);
727 source
= prefix_roota(prefix
, source
);
730 return portable_changes_add(changes
, n_changes
, type_or_errno
, path
, source
);
733 void portable_changes_free(PortableChange
*changes
, size_t n_changes
) {
736 assert(changes
|| n_changes
== 0);
738 for (i
= 0; i
< n_changes
; i
++) {
739 free(changes
[i
].path
);
740 free(changes
[i
].source
);
746 static const char *root_setting_from_image(ImageType type
) {
747 return IN_SET(type
, IMAGE_DIRECTORY
, IMAGE_SUBVOLUME
) ? "RootDirectory=" : "RootImage=";
750 static int make_marker_text(const char *image_path
, OrderedHashmap
*extension_images
, char **ret_text
) {
751 _cleanup_free_
char *text
= NULL
, *escaped_image_path
= NULL
;
757 escaped_image_path
= xescape(image_path
, ":");
758 if (!escaped_image_path
)
761 /* If the image is layered, include all layers in the marker as a colon-separated
762 * list of paths, so that we can do exact matches on removal. */
763 text
= strjoin(PORTABLE_DROPIN_MARKER_BEGIN
, escaped_image_path
);
767 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
768 _cleanup_free_
char *escaped
= NULL
;
770 escaped
= xescape(ext
->path
, ":");
774 if (!strextend(&text
, ":", escaped
))
778 if (!strextend(&text
, PORTABLE_DROPIN_MARKER_END
"\n"))
781 *ret_text
= TAKE_PTR(text
);
785 static int install_chroot_dropin(
786 const char *image_path
,
788 OrderedHashmap
*extension_images
,
789 const PortableMetadata
*m
,
790 const char *dropin_dir
,
792 PortableChange
**changes
,
795 _cleanup_free_
char *text
= NULL
, *dropin
= NULL
;
803 dropin
= path_join(dropin_dir
, "20-portable.conf");
807 r
= make_marker_text(image_path
, extension_images
, &text
);
809 return log_debug_errno(r
, "Failed to generate marker string for portable drop-in: %m");
811 if (endswith(m
->name
, ".service")) {
812 const char *os_release_source
, *root_type
;
813 _cleanup_free_
char *base_name
= NULL
;
815 root_type
= root_setting_from_image(type
);
817 if (access("/etc/os-release", F_OK
) < 0) {
819 return log_debug_errno(errno
, "Failed to check if /etc/os-release exists: %m");
821 os_release_source
= "/usr/lib/os-release";
823 os_release_source
= "/etc/os-release";
825 r
= path_extract_filename(m
->image_path
?: image_path
, &base_name
);
827 return log_debug_errno(r
, "Failed to extract basename from '%s': %m", m
->image_path
?: image_path
);
829 if (!strextend(&text
,
832 root_type
, image_path
, "\n"
833 "Environment=PORTABLE=", base_name
, "\n"
834 "BindReadOnlyPaths=", os_release_source
, ":/run/host/os-release\n"
835 "LogExtraFields=PORTABLE=", base_name
, "\n"))
838 if (m
->image_path
&& !path_equal(m
->image_path
, image_path
))
839 ORDERED_HASHMAP_FOREACH(ext
, extension_images
)
840 if (!strextend(&text
, "ExtensionImages=", ext
->path
, "\n"))
844 r
= write_string_file(dropin
, text
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
846 return log_debug_errno(r
, "Failed to write '%s': %m", dropin
);
848 (void) portable_changes_add(changes
, n_changes
, PORTABLE_WRITE
, dropin
, NULL
);
851 *ret_dropin
= TAKE_PTR(dropin
);
856 static int find_profile(const char *name
, const char *unit
, char **ret
) {
862 assert_se(dot
= strrchr(unit
, '.'));
864 NULSTR_FOREACH(p
, profile_dirs
) {
865 _cleanup_free_
char *joined
= NULL
;
867 joined
= strjoin(p
, "/", name
, "/", dot
+ 1, ".conf");
871 if (laccess(joined
, F_OK
) >= 0) {
872 *ret
= TAKE_PTR(joined
);
883 static int install_profile_dropin(
884 const char *image_path
,
885 const PortableMetadata
*m
,
886 const char *dropin_dir
,
890 PortableChange
**changes
,
893 _cleanup_free_
char *dropin
= NULL
, *from
= NULL
;
903 r
= find_profile(profile
, m
->name
, &from
);
906 return log_debug_errno(errno
, "Profile '%s' is not accessible: %m", profile
);
908 log_debug_errno(errno
, "Skipping link to profile '%s', as it does not exist: %m", profile
);
912 dropin
= path_join(dropin_dir
, "10-profile.conf");
916 if (flags
& PORTABLE_PREFER_COPY
) {
918 r
= copy_file_atomic(from
, dropin
, 0644, 0, 0, COPY_REFLINK
);
920 return log_debug_errno(r
, "Failed to copy %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW
), dropin
);
922 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, dropin
, from
);
926 if (symlink(from
, dropin
) < 0)
927 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW
), dropin
);
929 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, dropin
, from
);
933 *ret_dropin
= TAKE_PTR(dropin
);
938 static const char *attached_path(const LookupPaths
*paths
, PortableFlags flags
) {
943 if (flags
& PORTABLE_RUNTIME
)
944 where
= paths
->runtime_attached
;
946 where
= paths
->persistent_attached
;
952 static int attach_unit_file(
953 const LookupPaths
*paths
,
954 const char *image_path
,
956 OrderedHashmap
*extension_images
,
957 const PortableMetadata
*m
,
960 PortableChange
**changes
,
963 _cleanup_(unlink_and_freep
) char *chroot_dropin
= NULL
, *profile_dropin
= NULL
;
964 _cleanup_(rmdir_and_freep
) char *dropin_dir
= NULL
;
965 const char *where
, *path
;
971 assert(PORTABLE_METADATA_IS_UNIT(m
));
973 where
= attached_path(paths
, flags
);
975 (void) mkdir_parents(where
, 0755);
976 if (mkdir(where
, 0755) < 0) {
980 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, where
, NULL
);
982 path
= prefix_roota(where
, m
->name
);
983 dropin_dir
= strjoin(path
, ".d");
987 if (mkdir(dropin_dir
, 0755) < 0) {
991 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, dropin_dir
, NULL
);
993 /* We install the drop-ins first, and the actual unit file last to achieve somewhat atomic behaviour if PID 1
994 * is reloaded while we are creating things here: as long as only the drop-ins exist the unit doesn't exist at
997 r
= install_chroot_dropin(image_path
, type
, extension_images
, m
, dropin_dir
, &chroot_dropin
, changes
, n_changes
);
1001 r
= install_profile_dropin(image_path
, m
, dropin_dir
, profile
, flags
, &profile_dropin
, changes
, n_changes
);
1005 if ((flags
& PORTABLE_PREFER_SYMLINK
) && m
->source
) {
1007 if (symlink(m
->source
, path
) < 0)
1008 return log_debug_errno(errno
, "Failed to symlink unit file '%s': %m", path
);
1010 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, path
, m
->source
);
1013 _cleanup_(unlink_and_freep
) char *tmp
= NULL
;
1014 _cleanup_close_
int fd
= -1;
1016 fd
= open_tmpfile_linkable(path
, O_WRONLY
|O_CLOEXEC
, &tmp
);
1018 return log_debug_errno(fd
, "Failed to create unit file '%s': %m", path
);
1020 r
= copy_bytes(m
->fd
, fd
, UINT64_MAX
, COPY_REFLINK
);
1022 return log_debug_errno(r
, "Failed to copy unit file '%s': %m", path
);
1024 if (fchmod(fd
, 0644) < 0)
1025 return log_debug_errno(errno
, "Failed to change unit file access mode for '%s': %m", path
);
1027 r
= link_tmpfile(fd
, tmp
, path
);
1029 return log_debug_errno(r
, "Failed to install unit file '%s': %m", path
);
1033 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, path
, m
->source
);
1036 /* All is established now, now let's disable any rollbacks */
1037 chroot_dropin
= mfree(chroot_dropin
);
1038 profile_dropin
= mfree(profile_dropin
);
1039 dropin_dir
= mfree(dropin_dir
);
1044 static int image_symlink(
1045 const char *image_path
,
1046 PortableFlags flags
,
1049 const char *fn
, *where
;
1050 char *joined
= NULL
;
1055 fn
= last_path_component(image_path
);
1057 if (flags
& PORTABLE_RUNTIME
)
1058 where
= "/run/portables/";
1060 where
= "/etc/portables/";
1062 joined
= strjoin(where
, fn
);
1070 static int install_image_symlink(
1071 const char *image_path
,
1072 PortableFlags flags
,
1073 PortableChange
**changes
,
1074 size_t *n_changes
) {
1076 _cleanup_free_
char *sl
= NULL
;
1081 /* If the image is outside of the image search also link it into it, so that it can be found with short image
1082 * names and is listed among the images. */
1084 if (image_in_search_path(IMAGE_PORTABLE
, NULL
, image_path
))
1087 r
= image_symlink(image_path
, flags
, &sl
);
1089 return log_debug_errno(r
, "Failed to generate image symlink path: %m");
1091 (void) mkdir_parents(sl
, 0755);
1093 if (symlink(image_path
, sl
) < 0)
1094 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", image_path
, special_glyph(SPECIAL_GLYPH_ARROW
), sl
);
1096 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, sl
, image_path
);
1100 static int install_image_and_extensions_symlinks(
1102 OrderedHashmap
*extension_images
,
1103 PortableFlags flags
,
1104 PortableChange
**changes
,
1105 size_t *n_changes
) {
1112 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
1113 r
= install_image_symlink(ext
->path
, flags
, changes
, n_changes
);
1118 r
= install_image_symlink(image
->path
, flags
, changes
, n_changes
);
1125 int portable_attach(
1127 const char *name_or_path
,
1129 const char *profile
,
1130 char **extension_image_paths
,
1131 PortableFlags flags
,
1132 PortableChange
**changes
,
1134 sd_bus_error
*error
) {
1136 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
;
1137 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
1138 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1139 _cleanup_(image_unrefp
) Image
*image
= NULL
;
1140 PortableMetadata
*item
;
1145 assert(name_or_path
);
1147 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, NULL
, &image
);
1150 if (!strv_isempty(extension_image_paths
)) {
1151 extension_images
= ordered_hashmap_new(&image_hash_ops
);
1152 if (!extension_images
)
1155 STRV_FOREACH(p
, extension_image_paths
) {
1156 _cleanup_(image_unrefp
) Image
*new = NULL
;
1158 r
= image_find_harder(IMAGE_PORTABLE
, *p
, NULL
, &new);
1162 r
= ordered_hashmap_put(extension_images
, new->name
, new);
1169 r
= portable_extract_by_path(image
->path
, true, matches
, NULL
, &unit_files
, error
);
1173 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
1174 _cleanup_hashmap_free_ Hashmap
*extra_unit_files
= NULL
;
1176 r
= portable_extract_by_path(ext
->path
, false, matches
, NULL
, &extra_unit_files
, error
);
1179 r
= hashmap_move(unit_files
, extra_unit_files
);
1184 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1188 HASHMAP_FOREACH(item
, unit_files
) {
1189 r
= unit_file_exists(UNIT_FILE_SYSTEM
, &paths
, item
->name
);
1191 return sd_bus_error_set_errnof(error
, r
, "Failed to determine whether unit '%s' exists on the host: %m", item
->name
);
1192 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1193 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' exists on the host already, refusing.", item
->name
);
1195 r
= unit_file_is_active(bus
, item
->name
, error
);
1198 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1199 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active already, refusing.", item
->name
);
1202 HASHMAP_FOREACH(item
, unit_files
) {
1203 r
= attach_unit_file(&paths
, image
->path
, image
->type
, extension_images
,
1204 item
, profile
, flags
, changes
, n_changes
);
1209 /* We don't care too much for the image symlink, it's just a convenience thing, it's not necessary for proper
1210 * operation otherwise. */
1211 (void) install_image_and_extensions_symlinks(image
, extension_images
, flags
, changes
, n_changes
);
1216 static bool marker_matches_images(const char *marker
, const char *name_or_path
, char **extension_image_paths
) {
1217 _cleanup_strv_free_
char **root_and_extensions
= NULL
;
1218 char **image_name_or_path
;
1223 assert(name_or_path
);
1225 /* If extensions were used when attaching, the marker will be a colon-separated
1226 * list of images/paths. We enforce strict 1:1 matching, so that we are sure
1227 * we are detaching exactly what was attached.
1228 * For each image, starting with the root, we look for a token in the marker,
1229 * and return a negative answer on any non-matching combination. */
1231 root_and_extensions
= strv_new(name_or_path
);
1232 if (!root_and_extensions
)
1235 r
= strv_extend_strv(&root_and_extensions
, extension_image_paths
, false);
1239 STRV_FOREACH(image_name_or_path
, root_and_extensions
) {
1240 _cleanup_free_
char *image
= NULL
;
1242 r
= extract_first_word(&marker
, &image
, ":", EXTRACT_UNQUOTE
|EXTRACT_RETAIN_ESCAPE
);
1244 return log_debug_errno(r
, "Failed to parse marker: %s", marker
);
1248 a
= last_path_component(image
);
1250 if (image_name_is_valid(*image_name_or_path
)) {
1251 const char *e
, *underscore
;
1253 /* We shall match against an image name. In that case let's compare the last component, and optionally
1254 * allow either a suffix of ".raw" or a series of "/".
1255 * But allow matching on a different version of the same image, when a "_" is used as a separator. */
1256 underscore
= strchr(*image_name_or_path
, '_');
1258 if (strneq(a
, *image_name_or_path
, underscore
- *image_name_or_path
))
1263 e
= startswith(a
, *image_name_or_path
);
1267 if(!(e
[strspn(e
, "/")] == 0 || streq(e
, ".raw")))
1270 const char *b
, *underscore
;
1273 /* We shall match against a path. Let's ignore any prefix here though, as often there are many ways to
1274 * reach the same file. However, in this mode, let's validate any file suffix. */
1276 l
= strcspn(a
, "/");
1277 b
= last_path_component(*image_name_or_path
);
1279 if (strcspn(b
, "/") != l
)
1282 underscore
= strchr(b
, '_');
1286 if (!strneq(a
, b
, l
))
1294 static int test_chroot_dropin(
1298 const char *name_or_path
,
1299 char **extension_image_paths
,
1300 char **ret_marker
) {
1302 _cleanup_free_
char *line
= NULL
, *marker
= NULL
;
1303 _cleanup_fclose_
FILE *f
= NULL
;
1304 _cleanup_close_
int fd
= -1;
1305 const char *p
, *e
, *k
;
1312 /* We recognize unis created from portable images via the drop-in we created for them */
1314 p
= strjoina(fname
, ".d/20-portable.conf");
1315 fd
= openat(dirfd(d
), p
, O_RDONLY
|O_CLOEXEC
);
1317 if (errno
== ENOENT
)
1320 return log_debug_errno(errno
, "Failed to open %s/%s: %m", where
, p
);
1323 r
= take_fdopen_unlocked(&fd
, "r", &f
);
1325 return log_debug_errno(r
, "Failed to convert file handle: %m");
1327 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1329 return log_debug_errno(r
, "Failed to read from %s/%s: %m", where
, p
);
1331 e
= startswith(line
, PORTABLE_DROPIN_MARKER_BEGIN
);
1335 k
= endswith(e
, PORTABLE_DROPIN_MARKER_END
);
1339 marker
= strndup(e
, k
- e
);
1346 r
= marker_matches_images(marker
, name_or_path
, extension_image_paths
);
1349 *ret_marker
= TAKE_PTR(marker
);
1354 int portable_detach(
1356 const char *name_or_path
,
1357 char **extension_image_paths
,
1358 PortableFlags flags
,
1359 PortableChange
**changes
,
1361 sd_bus_error
*error
) {
1363 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1364 _cleanup_set_free_ Set
*unit_files
= NULL
, *markers
= NULL
;
1365 _cleanup_closedir_
DIR *d
= NULL
;
1366 const char *where
, *item
;
1371 assert(name_or_path
);
1373 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1377 where
= attached_path(&paths
, flags
);
1381 if (errno
== ENOENT
)
1384 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1387 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1388 _cleanup_free_
char *marker
= NULL
;
1389 UnitFileState state
;
1391 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1394 /* Filter out duplicates */
1395 if (set_contains(unit_files
, de
->d_name
))
1398 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1401 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, extension_image_paths
, &marker
);
1407 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1409 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1410 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_RUNTIME
, UNIT_FILE_LINKED_RUNTIME
))
1411 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
));
1413 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1416 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1417 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active, can't detach.", de
->d_name
);
1419 r
= set_put_strdup(&unit_files
, de
->d_name
);
1421 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1423 for (const char *p
= marker
;;) {
1424 _cleanup_free_
char *image
= NULL
;
1426 r
= extract_first_word(&p
, &image
, ":", EXTRACT_UNESCAPE_SEPARATORS
|EXTRACT_RETAIN_ESCAPE
);
1428 return log_debug_errno(r
, "Failed to parse marker: %s", p
);
1432 if (path_is_absolute(image
) && !image_in_search_path(IMAGE_PORTABLE
, NULL
, image
)) {
1433 r
= set_ensure_consume(&markers
, &path_hash_ops_free
, TAKE_PTR(image
));
1440 if (set_isempty(unit_files
))
1443 SET_FOREACH(item
, unit_files
) {
1444 _cleanup_free_
char *md
= NULL
;
1447 if (unlinkat(dirfd(d
), item
, 0) < 0) {
1448 log_debug_errno(errno
, "Can't remove unit file %s/%s: %m", where
, item
);
1450 if (errno
!= ENOENT
&& ret
>= 0)
1453 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, item
, NULL
);
1455 FOREACH_STRING(suffix
, ".d/10-profile.conf", ".d/20-portable.conf") {
1456 _cleanup_free_
char *dropin
= NULL
;
1458 dropin
= strjoin(item
, suffix
);
1462 if (unlinkat(dirfd(d
), dropin
, 0) < 0) {
1463 log_debug_errno(errno
, "Can't remove drop-in %s/%s: %m", where
, dropin
);
1465 if (errno
!= ENOENT
&& ret
>= 0)
1468 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, dropin
, NULL
);
1471 md
= strjoin(item
, ".d");
1475 if (unlinkat(dirfd(d
), md
, AT_REMOVEDIR
) < 0) {
1476 log_debug_errno(errno
, "Can't remove drop-in directory %s/%s: %m", where
, md
);
1478 if (errno
!= ENOENT
&& ret
>= 0)
1481 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, md
, NULL
);
1484 /* Now, also drop any image symlink, for images outside of the sarch path */
1485 SET_FOREACH(item
, markers
) {
1486 _cleanup_free_
char *sl
= NULL
;
1489 r
= image_symlink(item
, flags
, &sl
);
1491 log_debug_errno(r
, "Failed to determine image symlink for '%s', ignoring: %m", item
);
1495 if (lstat(sl
, &st
) < 0) {
1496 log_debug_errno(errno
, "Failed to stat '%s', ignoring: %m", sl
);
1500 if (!S_ISLNK(st
.st_mode
)) {
1501 log_debug("Image '%s' is not a symlink, ignoring.", sl
);
1505 if (unlink(sl
) < 0) {
1506 log_debug_errno(errno
, "Can't remove image symlink '%s': %m", sl
);
1508 if (errno
!= ENOENT
&& ret
>= 0)
1511 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, sl
, NULL
);
1514 /* Try to remove the unit file directory, if we can */
1515 if (rmdir(where
) >= 0)
1516 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, where
, NULL
);
1521 log_debug("No unit files associated with '%s' found. Image not attached?", name_or_path
);
1522 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_UNIT
, "No unit files associated with '%s' found. Image not attached?", name_or_path
);
1525 static int portable_get_state_internal(
1527 const char *name_or_path
,
1528 PortableFlags flags
,
1530 sd_bus_error
*error
) {
1532 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1533 bool found_enabled
= false, found_running
= false;
1534 _cleanup_set_free_ Set
*unit_files
= NULL
;
1535 _cleanup_closedir_
DIR *d
= NULL
;
1540 assert(name_or_path
);
1543 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1547 where
= attached_path(&paths
, flags
);
1551 if (errno
== ENOENT
) {
1552 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1553 *ret
= PORTABLE_DETACHED
;
1557 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1560 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1561 UnitFileState state
;
1563 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1566 /* Filter out duplicates */
1567 if (set_contains(unit_files
, de
->d_name
))
1570 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1573 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, NULL
, NULL
);
1579 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1581 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1582 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_LINKED_RUNTIME
))
1583 found_enabled
= true;
1585 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1589 found_running
= true;
1591 r
= set_put_strdup(&unit_files
, de
->d_name
);
1593 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1596 *ret
= found_running
? (!set_isempty(unit_files
) && (flags
& PORTABLE_RUNTIME
) ? PORTABLE_RUNNING_RUNTIME
: PORTABLE_RUNNING
) :
1597 found_enabled
? (flags
& PORTABLE_RUNTIME
? PORTABLE_ENABLED_RUNTIME
: PORTABLE_ENABLED
) :
1598 !set_isempty(unit_files
) ? (flags
& PORTABLE_RUNTIME
? PORTABLE_ATTACHED_RUNTIME
: PORTABLE_ATTACHED
) : PORTABLE_DETACHED
;
1603 int portable_get_state(
1605 const char *name_or_path
,
1606 PortableFlags flags
,
1608 sd_bus_error
*error
) {
1610 PortableState state
;
1613 assert(name_or_path
);
1616 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1617 * the latter only if we didn't find anything in the former. */
1619 r
= portable_get_state_internal(bus
, name_or_path
, flags
& ~PORTABLE_RUNTIME
, &state
, error
);
1623 if (state
== PORTABLE_DETACHED
) {
1624 r
= portable_get_state_internal(bus
, name_or_path
, flags
| PORTABLE_RUNTIME
, &state
, error
);
1633 int portable_get_profiles(char ***ret
) {
1636 return conf_files_list_nulstr(ret
, NULL
, NULL
, CONF_FILES_DIRECTORY
|CONF_FILES_BASENAME
|CONF_FILES_FILTER_MASKED
, profile_dirs
);
1639 static const char* const portable_change_type_table
[_PORTABLE_CHANGE_TYPE_MAX
] = {
1640 [PORTABLE_COPY
] = "copy",
1641 [PORTABLE_MKDIR
] = "mkdir",
1642 [PORTABLE_SYMLINK
] = "symlink",
1643 [PORTABLE_UNLINK
] = "unlink",
1644 [PORTABLE_WRITE
] = "write",
1647 DEFINE_STRING_TABLE_LOOKUP(portable_change_type
, int);
1649 static const char* const portable_state_table
[_PORTABLE_STATE_MAX
] = {
1650 [PORTABLE_DETACHED
] = "detached",
1651 [PORTABLE_ATTACHED
] = "attached",
1652 [PORTABLE_ATTACHED_RUNTIME
] = "attached-runtime",
1653 [PORTABLE_ENABLED
] = "enabled",
1654 [PORTABLE_ENABLED_RUNTIME
] = "enabled-runtime",
1655 [PORTABLE_RUNNING
] = "running",
1656 [PORTABLE_RUNNING_RUNTIME
] = "running-runtime",
1659 DEFINE_STRING_TABLE_LOOKUP(portable_state
, PortableState
);