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
);
95 strcpy(m
->name
, name
);
101 PortableMetadata
*portable_metadata_unref(PortableMetadata
*i
) {
112 static int compare_metadata(PortableMetadata
*const *x
, PortableMetadata
*const *y
) {
113 return strcmp((*x
)->name
, (*y
)->name
);
116 int portable_metadata_hashmap_to_sorted_array(Hashmap
*unit_files
, PortableMetadata
***ret
) {
118 _cleanup_free_ PortableMetadata
**sorted
= NULL
;
119 PortableMetadata
*item
;
122 sorted
= new(PortableMetadata
*, hashmap_size(unit_files
));
126 HASHMAP_FOREACH(item
, unit_files
)
129 assert(k
== hashmap_size(unit_files
));
131 typesafe_qsort(sorted
, k
, compare_metadata
);
133 *ret
= TAKE_PTR(sorted
);
137 static int send_item(
142 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
= {};
145 .msg_control
= &control
,
146 .msg_controllen
= sizeof(control
),
150 struct cmsghdr
*cmsg
;
151 _cleanup_close_
int data_fd
= -1;
153 assert(socket_fd
>= 0);
157 data_fd
= copy_data_fd(fd
);
161 cmsg
= CMSG_FIRSTHDR(&mh
);
162 cmsg
->cmsg_level
= SOL_SOCKET
;
163 cmsg
->cmsg_type
= SCM_RIGHTS
;
164 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
165 memcpy(CMSG_DATA(cmsg
), &data_fd
, sizeof(int));
167 iovec
= IOVEC_MAKE_STRING(name
);
169 if (sendmsg(socket_fd
, &mh
, MSG_NOSIGNAL
) < 0)
175 static int recv_item(
180 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
;
181 char buffer
[PATH_MAX
+2];
182 struct iovec iov
= IOVEC_INIT(buffer
, sizeof(buffer
)-1);
184 .msg_control
= &control
,
185 .msg_controllen
= sizeof(control
),
189 struct cmsghdr
*cmsg
;
190 _cleanup_close_
int found_fd
= -1;
194 assert(socket_fd
>= 0);
198 n
= recvmsg_safe(socket_fd
, &mh
, MSG_CMSG_CLOEXEC
);
202 CMSG_FOREACH(cmsg
, &mh
) {
203 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
204 cmsg
->cmsg_type
== SCM_RIGHTS
) {
206 if (cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
207 assert(found_fd
< 0);
208 found_fd
= *(int*) CMSG_DATA(cmsg
);
219 copy
= strdup(buffer
);
224 *ret_fd
= TAKE_FD(found_fd
);
229 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(portable_metadata_hash_ops
, char, string_hash_func
, string_compare_func
,
230 PortableMetadata
, portable_metadata_unref
);
232 static int extract_now(
236 PortableMetadata
**ret_os_release
,
237 Hashmap
**ret_unit_files
) {
239 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
240 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
241 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
242 _cleanup_close_
int os_release_fd
= -1;
243 _cleanup_free_
char *os_release_path
= NULL
;
247 /* Extracts the metadata from a directory tree 'where'. Extracts two kinds of information: the /etc/os-release
248 * data, and all unit files matching the specified expression. Note that this function is called in two very
249 * different but also similar contexts. When the tool gets invoked on a directory tree, we'll process it
250 * directly, and in-process, and thus can return the requested data directly, via 'ret_os_release' and
251 * 'ret_unit_files'. However, if the tool is invoked on a raw disk image — which needs to be mounted first — we
252 * are invoked in a child process with private mounts and then need to send the collected data to our
253 * parent. To handle both cases in one call this function also gets a 'socket_fd' parameter, which when >= 0 is
254 * used to send the data to the parent. */
258 /* First, find /etc/os-release and send it upstream (or just save it). */
259 r
= open_os_release(where
, &os_release_path
, &os_release_fd
);
261 log_debug_errno(r
, "Couldn't acquire os-release file, ignoring: %m");
263 if (socket_fd
>= 0) {
264 r
= send_item(socket_fd
, "/etc/os-release", os_release_fd
);
266 return log_debug_errno(r
, "Failed to send os-release file: %m");
269 if (ret_os_release
) {
270 os_release
= portable_metadata_new("/etc/os-release", NULL
, os_release_fd
);
275 os_release
->source
= TAKE_PTR(os_release_path
);
279 /* Then, send unit file data to the parent (or/and add it to the hashmap). For that we use our usual unit
280 * discovery logic. Note that we force looking inside of /lib/systemd/system/ for units too, as we mightbe
281 * compiled for a split-usr system but the image might be a legacy-usr one. */
282 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, where
);
284 return log_debug_errno(r
, "Failed to acquire lookup paths: %m");
286 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
290 STRV_FOREACH(i
, paths
.search_path
) {
291 _cleanup_free_
char *resolved
= NULL
;
292 _cleanup_closedir_
DIR *d
= NULL
;
295 r
= chase_symlinks_and_opendir(*i
, where
, 0, &resolved
, &d
);
297 log_debug_errno(r
, "Failed to open unit path '%s', ignoring: %m", *i
);
301 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to read directory: %m")) {
302 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*m
= NULL
;
303 _cleanup_close_
int fd
= -1;
305 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
308 if (!unit_match(de
->d_name
, matches
))
311 /* Filter out duplicates */
312 if (hashmap_get(unit_files
, de
->d_name
))
315 dirent_ensure_type(d
, de
);
316 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
319 fd
= openat(dirfd(d
), de
->d_name
, O_CLOEXEC
|O_RDONLY
);
321 log_debug_errno(errno
, "Failed to open unit file '%s', ignoring: %m", de
->d_name
);
325 if (socket_fd
>= 0) {
326 r
= send_item(socket_fd
, de
->d_name
, fd
);
328 return log_debug_errno(r
, "Failed to send unit metadata to parent: %m");
331 m
= portable_metadata_new(de
->d_name
, NULL
, fd
);
336 m
->source
= path_join(resolved
, de
->d_name
);
340 r
= hashmap_put(unit_files
, m
->name
, m
);
342 return log_debug_errno(r
, "Failed to add unit to hashmap: %m");
348 *ret_os_release
= TAKE_PTR(os_release
);
350 *ret_unit_files
= TAKE_PTR(unit_files
);
355 static int portable_extract_by_path(
357 bool extract_os_release
,
359 PortableMetadata
**ret_os_release
,
360 Hashmap
**ret_unit_files
,
361 sd_bus_error
*error
) {
363 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
364 _cleanup_(portable_metadata_unrefp
) PortableMetadata
* os_release
= NULL
;
365 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
370 r
= loop_device_make_by_path(path
, O_RDONLY
, LO_FLAGS_PARTSCAN
, &d
);
372 /* We can't turn this into a loop-back block device, and this returns EISDIR? Then this is a directory
373 * tree and not a raw device. It's easy then. */
375 r
= extract_now(path
, matches
, -1, &os_release
, &unit_files
);
380 return log_debug_errno(r
, "Failed to set up loopback device for %s: %m", path
);
382 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
383 _cleanup_(rmdir_and_freep
) char *tmpdir
= NULL
;
384 _cleanup_(close_pairp
) int seq
[2] = { -1, -1 };
385 _cleanup_(sigkill_waitp
) pid_t child
= 0;
387 /* We now have a loopback block device, let's fork off a child in its own mount namespace, mount it
388 * there, and extract the metadata we need. The metadata is sent from the child back to us. */
390 BLOCK_SIGNALS(SIGCHLD
);
392 r
= mkdtemp_malloc("/tmp/inspect-XXXXXX", &tmpdir
);
394 return log_debug_errno(r
, "Failed to create temporary directory: %m");
399 d
->uevent_seqnum_not_before
,
400 d
->timestamp_not_before
,
401 DISSECT_IMAGE_READ_ONLY
|
402 DISSECT_IMAGE_GENERIC_ROOT
|
403 DISSECT_IMAGE_REQUIRE_ROOT
|
404 DISSECT_IMAGE_DISCARD_ON_LOOP
|
405 DISSECT_IMAGE_RELAX_VAR_CHECK
|
406 DISSECT_IMAGE_USR_NO_ROOT
,
409 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't identify a suitable partition table or file system in '%s'.", path
);
410 else if (r
== -EADDRNOTAVAIL
)
411 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No root partition for specified root hash found in '%s'.", path
);
412 else if (r
== -ENOTUNIQ
)
413 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Multiple suitable root partitions found in image '%s'.", path
);
414 else if (r
== -ENXIO
)
415 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No suitable root partition found in image '%s'.", path
);
416 else if (r
== -EPROTONOSUPPORT
)
417 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
);
421 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, seq
) < 0)
422 return log_debug_errno(errno
, "Failed to allocated SOCK_SEQPACKET socket: %m");
424 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
|FORK_LOG
, &child
);
428 seq
[0] = safe_close(seq
[0]);
430 r
= dissected_image_mount(m
, tmpdir
, UID_INVALID
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
);
432 log_debug_errno(r
, "Failed to mount dissected image: %m");
436 r
= extract_now(tmpdir
, matches
, seq
[1], NULL
, NULL
);
439 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
442 seq
[1] = safe_close(seq
[1]);
444 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
449 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*add
= NULL
;
450 _cleanup_free_
char *name
= NULL
;
451 _cleanup_close_
int fd
= -1;
453 r
= recv_item(seq
[0], &name
, &fd
);
455 return log_debug_errno(r
, "Failed to receive item: %m");
457 /* We can't really distinguish a zero-length datagram without any fds from EOF (both are signalled the
458 * same way by recvmsg()). Hence, accept either as end notification. */
459 if (isempty(name
) && fd
< 0)
462 if (isempty(name
) || fd
< 0)
463 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
464 "Invalid item sent from child.");
466 add
= portable_metadata_new(name
, path
, fd
);
471 /* Note that we do not initialize 'add->source' here, as the source path is not usable here as
472 * it refers to a path only valid in the short-living namespaced child process we forked
475 if (PORTABLE_METADATA_IS_UNIT(add
)) {
476 r
= hashmap_put(unit_files
, add
->name
, add
);
478 return log_debug_errno(r
, "Failed to add item to unit file list: %m");
482 } else if (PORTABLE_METADATA_IS_OS_RELEASE(add
)) {
485 os_release
= TAKE_PTR(add
);
487 assert_not_reached("Unexpected metadata item from child.");
490 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
496 /* When the portable image is layered, the image with units will not
497 * have a full filesystem, so no os-release - it will be in the root layer */
498 if (extract_os_release
&& !os_release
)
499 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Image '%s' lacks os-release data, refusing.", path
);
501 if (!extract_os_release
&& hashmap_isempty(unit_files
))
502 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't find any matching unit files in image '%s', refusing.", path
);
505 *ret_unit_files
= TAKE_PTR(unit_files
);
508 *ret_os_release
= TAKE_PTR(os_release
);
513 int portable_extract(
514 const char *name_or_path
,
516 char **extension_image_paths
,
517 PortableMetadata
**ret_os_release
,
518 Hashmap
**ret_unit_files
,
519 sd_bus_error
*error
) {
521 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
522 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
;
523 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
524 _cleanup_(image_unrefp
) Image
*image
= NULL
;
528 assert(name_or_path
);
530 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, NULL
, &image
);
534 if (!strv_isempty(extension_image_paths
)) {
537 extension_images
= ordered_hashmap_new(&image_hash_ops
);
538 if (!extension_images
)
541 STRV_FOREACH(p
, extension_image_paths
) {
542 _cleanup_(image_unrefp
) Image
*new = NULL
;
544 r
= image_find_harder(IMAGE_PORTABLE
, *p
, NULL
, &new);
548 r
= ordered_hashmap_put(extension_images
, new->name
, new);
555 r
= portable_extract_by_path(image
->path
, true, matches
, &os_release
, &unit_files
, error
);
559 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
560 _cleanup_hashmap_free_ Hashmap
*extra_unit_files
= NULL
;
562 r
= portable_extract_by_path(ext
->path
, false, matches
, NULL
, &extra_unit_files
, error
);
565 r
= hashmap_move(unit_files
, extra_unit_files
);
570 *ret_os_release
= TAKE_PTR(os_release
);
571 *ret_unit_files
= TAKE_PTR(unit_files
);
576 static int unit_file_is_active(
579 sd_bus_error
*error
) {
581 static const char *const active_states
[] = {
593 /* If we are looking at a plain or instance things are easy, we can just query the state */
594 if (unit_name_is_valid(name
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
)) {
595 _cleanup_free_
char *path
= NULL
, *buf
= NULL
;
597 path
= unit_dbus_path_from_name(name
);
601 r
= sd_bus_get_property_string(
603 "org.freedesktop.systemd1",
605 "org.freedesktop.systemd1.Unit",
610 return log_debug_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(error
, r
));
612 return strv_contains((char**) active_states
, buf
);
615 /* Otherwise we need to enumerate. But let's build the most restricted query we can */
616 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
617 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
618 const char *at
, *prefix
, *joined
;
620 r
= sd_bus_message_new_method_call(
623 "org.freedesktop.systemd1",
624 "/org/freedesktop/systemd1",
625 "org.freedesktop.systemd1.Manager",
626 "ListUnitsByPatterns");
630 r
= sd_bus_message_append_strv(m
, (char**) active_states
);
634 at
= strchr(name
, '@');
637 prefix
= strndupa(name
, at
+ 1 - name
);
638 joined
= strjoina(prefix
, "*", at
+ 1);
640 r
= sd_bus_message_append_strv(m
, STRV_MAKE(joined
));
644 r
= sd_bus_call(bus
, m
, 0, error
, &reply
);
646 return log_debug_errno(r
, "Failed to list units: %s", bus_error_message(error
, r
));
648 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
652 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_STRUCT
, "ssssssouso");
662 static int portable_changes_add(
663 PortableChange
**changes
,
665 int type_or_errno
, /* PORTABLE_COPY, PORTABLE_SYMLINK, … if positive, or errno if negative */
667 const char *source
) {
669 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
673 assert(!changes
== !n_changes
);
675 if (type_or_errno
>= 0)
676 assert(type_or_errno
< _PORTABLE_CHANGE_TYPE_MAX
);
678 assert(type_or_errno
>= -ERRNO_MAX
);
683 c
= reallocarray(*changes
, *n_changes
+ 1, sizeof(PortableChange
));
702 c
[(*n_changes
)++] = (PortableChange
) {
703 .type_or_errno
= type_or_errno
,
705 .source
= TAKE_PTR(s
),
711 static int portable_changes_add_with_prefix(
712 PortableChange
**changes
,
717 const char *source
) {
720 assert(!changes
== !n_changes
);
726 path
= prefix_roota(prefix
, path
);
729 source
= prefix_roota(prefix
, source
);
732 return portable_changes_add(changes
, n_changes
, type_or_errno
, path
, source
);
735 void portable_changes_free(PortableChange
*changes
, size_t n_changes
) {
738 assert(changes
|| n_changes
== 0);
740 for (i
= 0; i
< n_changes
; i
++) {
741 free(changes
[i
].path
);
742 free(changes
[i
].source
);
748 static const char *root_setting_from_image(ImageType type
) {
749 return IN_SET(type
, IMAGE_DIRECTORY
, IMAGE_SUBVOLUME
) ? "RootDirectory=" : "RootImage=";
752 static int make_marker_text(const char *image_path
, OrderedHashmap
*extension_images
, char **ret_text
) {
753 _cleanup_free_
char *text
= NULL
, *escaped_image_path
= NULL
;
759 escaped_image_path
= xescape(image_path
, ":");
760 if (!escaped_image_path
)
763 /* If the image is layered, include all layers in the marker as a colon-separated
764 * list of paths, so that we can do exact matches on removal. */
765 text
= strjoin(PORTABLE_DROPIN_MARKER_BEGIN
, escaped_image_path
);
769 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
770 _cleanup_free_
char *escaped
= NULL
;
772 escaped
= xescape(ext
->path
, ":");
776 if (!strextend(&text
, ":", escaped
))
780 if (!strextend(&text
, PORTABLE_DROPIN_MARKER_END
"\n"))
783 *ret_text
= TAKE_PTR(text
);
787 static int install_chroot_dropin(
788 const char *image_path
,
790 OrderedHashmap
*extension_images
,
791 const PortableMetadata
*m
,
792 const char *dropin_dir
,
794 PortableChange
**changes
,
797 _cleanup_free_
char *text
= NULL
, *dropin
= NULL
;
805 dropin
= path_join(dropin_dir
, "20-portable.conf");
809 r
= make_marker_text(image_path
, extension_images
, &text
);
811 return log_debug_errno(r
, "Failed to generate marker string for portable drop-in: %m");
813 if (endswith(m
->name
, ".service")) {
814 const char *os_release_source
, *root_type
;
815 _cleanup_free_
char *base_name
= NULL
;
817 root_type
= root_setting_from_image(type
);
819 if (access("/etc/os-release", F_OK
) < 0) {
821 return log_debug_errno(errno
, "Failed to check if /etc/os-release exists: %m");
823 os_release_source
= "/usr/lib/os-release";
825 os_release_source
= "/etc/os-release";
827 r
= path_extract_filename(m
->image_path
?: image_path
, &base_name
);
829 return log_debug_errno(r
, "Failed to extract basename from '%s': %m", m
->image_path
?: image_path
);
831 if (!strextend(&text
,
834 root_type
, image_path
, "\n"
835 "Environment=PORTABLE=", base_name
, "\n"
836 "BindReadOnlyPaths=", os_release_source
, ":/run/host/os-release\n"
837 "LogExtraFields=PORTABLE=", base_name
, "\n"))
840 if (m
->image_path
&& !path_equal(m
->image_path
, image_path
))
841 ORDERED_HASHMAP_FOREACH(ext
, extension_images
)
842 if (!strextend(&text
, "ExtensionImages=", ext
->path
, "\n"))
846 r
= write_string_file(dropin
, text
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
848 return log_debug_errno(r
, "Failed to write '%s': %m", dropin
);
850 (void) portable_changes_add(changes
, n_changes
, PORTABLE_WRITE
, dropin
, NULL
);
853 *ret_dropin
= TAKE_PTR(dropin
);
858 static int find_profile(const char *name
, const char *unit
, char **ret
) {
864 assert_se(dot
= strrchr(unit
, '.'));
866 NULSTR_FOREACH(p
, profile_dirs
) {
867 _cleanup_free_
char *joined
= NULL
;
869 joined
= strjoin(p
, "/", name
, "/", dot
+ 1, ".conf");
873 if (laccess(joined
, F_OK
) >= 0) {
874 *ret
= TAKE_PTR(joined
);
885 static int install_profile_dropin(
886 const char *image_path
,
887 const PortableMetadata
*m
,
888 const char *dropin_dir
,
892 PortableChange
**changes
,
895 _cleanup_free_
char *dropin
= NULL
, *from
= NULL
;
905 r
= find_profile(profile
, m
->name
, &from
);
908 return log_debug_errno(errno
, "Profile '%s' is not accessible: %m", profile
);
910 log_debug_errno(errno
, "Skipping link to profile '%s', as it does not exist: %m", profile
);
914 dropin
= path_join(dropin_dir
, "10-profile.conf");
918 if (flags
& PORTABLE_PREFER_COPY
) {
920 r
= copy_file_atomic(from
, dropin
, 0644, 0, 0, COPY_REFLINK
);
922 return log_debug_errno(r
, "Failed to copy %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW
), dropin
);
924 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, dropin
, from
);
928 if (symlink(from
, dropin
) < 0)
929 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW
), dropin
);
931 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, dropin
, from
);
935 *ret_dropin
= TAKE_PTR(dropin
);
940 static const char *attached_path(const LookupPaths
*paths
, PortableFlags flags
) {
945 if (flags
& PORTABLE_RUNTIME
)
946 where
= paths
->runtime_attached
;
948 where
= paths
->persistent_attached
;
954 static int attach_unit_file(
955 const LookupPaths
*paths
,
956 const char *image_path
,
958 OrderedHashmap
*extension_images
,
959 const PortableMetadata
*m
,
962 PortableChange
**changes
,
965 _cleanup_(unlink_and_freep
) char *chroot_dropin
= NULL
, *profile_dropin
= NULL
;
966 _cleanup_(rmdir_and_freep
) char *dropin_dir
= NULL
;
967 const char *where
, *path
;
973 assert(PORTABLE_METADATA_IS_UNIT(m
));
975 where
= attached_path(paths
, flags
);
977 (void) mkdir_parents(where
, 0755);
978 if (mkdir(where
, 0755) < 0) {
982 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, where
, NULL
);
984 path
= prefix_roota(where
, m
->name
);
985 dropin_dir
= strjoin(path
, ".d");
989 if (mkdir(dropin_dir
, 0755) < 0) {
993 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, dropin_dir
, NULL
);
995 /* We install the drop-ins first, and the actual unit file last to achieve somewhat atomic behaviour if PID 1
996 * is reloaded while we are creating things here: as long as only the drop-ins exist the unit doesn't exist at
999 r
= install_chroot_dropin(image_path
, type
, extension_images
, m
, dropin_dir
, &chroot_dropin
, changes
, n_changes
);
1003 r
= install_profile_dropin(image_path
, m
, dropin_dir
, profile
, flags
, &profile_dropin
, changes
, n_changes
);
1007 if ((flags
& PORTABLE_PREFER_SYMLINK
) && m
->source
) {
1009 if (symlink(m
->source
, path
) < 0)
1010 return log_debug_errno(errno
, "Failed to symlink unit file '%s': %m", path
);
1012 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, path
, m
->source
);
1015 _cleanup_(unlink_and_freep
) char *tmp
= NULL
;
1016 _cleanup_close_
int fd
= -1;
1018 fd
= open_tmpfile_linkable(path
, O_WRONLY
|O_CLOEXEC
, &tmp
);
1020 return log_debug_errno(fd
, "Failed to create unit file '%s': %m", path
);
1022 r
= copy_bytes(m
->fd
, fd
, UINT64_MAX
, COPY_REFLINK
);
1024 return log_debug_errno(r
, "Failed to copy unit file '%s': %m", path
);
1026 if (fchmod(fd
, 0644) < 0)
1027 return log_debug_errno(errno
, "Failed to change unit file access mode for '%s': %m", path
);
1029 r
= link_tmpfile(fd
, tmp
, path
);
1031 return log_debug_errno(r
, "Failed to install unit file '%s': %m", path
);
1035 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, path
, m
->source
);
1038 /* All is established now, now let's disable any rollbacks */
1039 chroot_dropin
= mfree(chroot_dropin
);
1040 profile_dropin
= mfree(profile_dropin
);
1041 dropin_dir
= mfree(dropin_dir
);
1046 static int image_symlink(
1047 const char *image_path
,
1048 PortableFlags flags
,
1051 const char *fn
, *where
;
1052 char *joined
= NULL
;
1057 fn
= last_path_component(image_path
);
1059 if (flags
& PORTABLE_RUNTIME
)
1060 where
= "/run/portables/";
1062 where
= "/etc/portables/";
1064 joined
= strjoin(where
, fn
);
1072 static int install_image_symlink(
1073 const char *image_path
,
1074 PortableFlags flags
,
1075 PortableChange
**changes
,
1076 size_t *n_changes
) {
1078 _cleanup_free_
char *sl
= NULL
;
1083 /* If the image is outside of the image search also link it into it, so that it can be found with short image
1084 * names and is listed among the images. */
1086 if (image_in_search_path(IMAGE_PORTABLE
, NULL
, image_path
))
1089 r
= image_symlink(image_path
, flags
, &sl
);
1091 return log_debug_errno(r
, "Failed to generate image symlink path: %m");
1093 (void) mkdir_parents(sl
, 0755);
1095 if (symlink(image_path
, sl
) < 0)
1096 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", image_path
, special_glyph(SPECIAL_GLYPH_ARROW
), sl
);
1098 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, sl
, image_path
);
1102 static int install_image_and_extensions_symlinks(
1104 OrderedHashmap
*extension_images
,
1105 PortableFlags flags
,
1106 PortableChange
**changes
,
1107 size_t *n_changes
) {
1114 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
1115 r
= install_image_symlink(ext
->path
, flags
, changes
, n_changes
);
1120 r
= install_image_symlink(image
->path
, flags
, changes
, n_changes
);
1127 int portable_attach(
1129 const char *name_or_path
,
1131 const char *profile
,
1132 char **extension_image_paths
,
1133 PortableFlags flags
,
1134 PortableChange
**changes
,
1136 sd_bus_error
*error
) {
1138 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
;
1139 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
1140 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1141 _cleanup_(image_unrefp
) Image
*image
= NULL
;
1142 PortableMetadata
*item
;
1147 assert(name_or_path
);
1149 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, NULL
, &image
);
1152 if (!strv_isempty(extension_image_paths
)) {
1153 extension_images
= ordered_hashmap_new(&image_hash_ops
);
1154 if (!extension_images
)
1157 STRV_FOREACH(p
, extension_image_paths
) {
1158 _cleanup_(image_unrefp
) Image
*new = NULL
;
1160 r
= image_find_harder(IMAGE_PORTABLE
, *p
, NULL
, &new);
1164 r
= ordered_hashmap_put(extension_images
, new->name
, new);
1171 r
= portable_extract_by_path(image
->path
, true, matches
, NULL
, &unit_files
, error
);
1175 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
1176 _cleanup_hashmap_free_ Hashmap
*extra_unit_files
= NULL
;
1178 r
= portable_extract_by_path(ext
->path
, false, matches
, NULL
, &extra_unit_files
, error
);
1181 r
= hashmap_move(unit_files
, extra_unit_files
);
1186 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1190 HASHMAP_FOREACH(item
, unit_files
) {
1191 r
= unit_file_exists(UNIT_FILE_SYSTEM
, &paths
, item
->name
);
1193 return sd_bus_error_set_errnof(error
, r
, "Failed to determine whether unit '%s' exists on the host: %m", item
->name
);
1194 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1195 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' exists on the host already, refusing.", item
->name
);
1197 r
= unit_file_is_active(bus
, item
->name
, error
);
1200 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1201 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active already, refusing.", item
->name
);
1204 HASHMAP_FOREACH(item
, unit_files
) {
1205 r
= attach_unit_file(&paths
, image
->path
, image
->type
, extension_images
,
1206 item
, profile
, flags
, changes
, n_changes
);
1211 /* We don't care too much for the image symlink, it's just a convenience thing, it's not necessary for proper
1212 * operation otherwise. */
1213 (void) install_image_and_extensions_symlinks(image
, extension_images
, flags
, changes
, n_changes
);
1218 static bool marker_matches_images(const char *marker
, const char *name_or_path
, char **extension_image_paths
) {
1219 _cleanup_strv_free_
char **root_and_extensions
= NULL
;
1220 char **image_name_or_path
;
1225 assert(name_or_path
);
1227 /* If extensions were used when attaching, the marker will be a colon-separated
1228 * list of images/paths. We enforce strict 1:1 matching, so that we are sure
1229 * we are detaching exactly what was attached.
1230 * For each image, starting with the root, we look for a token in the marker,
1231 * and return a negative answer on any non-matching combination. */
1233 root_and_extensions
= strv_new(name_or_path
);
1234 if (!root_and_extensions
)
1237 r
= strv_extend_strv(&root_and_extensions
, extension_image_paths
, false);
1241 STRV_FOREACH(image_name_or_path
, root_and_extensions
) {
1242 _cleanup_free_
char *image
= NULL
;
1244 r
= extract_first_word(&marker
, &image
, ":", EXTRACT_UNQUOTE
|EXTRACT_RETAIN_ESCAPE
);
1246 return log_debug_errno(r
, "Failed to parse marker: %s", marker
);
1250 a
= last_path_component(image
);
1252 if (image_name_is_valid(*image_name_or_path
)) {
1253 const char *e
, *underscore
;
1255 /* We shall match against an image name. In that case let's compare the last component, and optionally
1256 * allow either a suffix of ".raw" or a series of "/".
1257 * But allow matching on a different version of the same image, when a "_" is used as a separator. */
1258 underscore
= strchr(*image_name_or_path
, '_');
1260 if (strneq(a
, *image_name_or_path
, underscore
- *image_name_or_path
))
1265 e
= startswith(a
, *image_name_or_path
);
1269 if(!(e
[strspn(e
, "/")] == 0 || streq(e
, ".raw")))
1272 const char *b
, *underscore
;
1275 /* We shall match against a path. Let's ignore any prefix here though, as often there are many ways to
1276 * reach the same file. However, in this mode, let's validate any file suffix. */
1278 l
= strcspn(a
, "/");
1279 b
= last_path_component(*image_name_or_path
);
1281 if (strcspn(b
, "/") != l
)
1284 underscore
= strchr(b
, '_');
1288 if (!strneq(a
, b
, l
))
1296 static int test_chroot_dropin(
1300 const char *name_or_path
,
1301 char **extension_image_paths
,
1302 char **ret_marker
) {
1304 _cleanup_free_
char *line
= NULL
, *marker
= NULL
;
1305 _cleanup_fclose_
FILE *f
= NULL
;
1306 _cleanup_close_
int fd
= -1;
1307 const char *p
, *e
, *k
;
1314 /* We recognize unis created from portable images via the drop-in we created for them */
1316 p
= strjoina(fname
, ".d/20-portable.conf");
1317 fd
= openat(dirfd(d
), p
, O_RDONLY
|O_CLOEXEC
);
1319 if (errno
== ENOENT
)
1322 return log_debug_errno(errno
, "Failed to open %s/%s: %m", where
, p
);
1325 r
= take_fdopen_unlocked(&fd
, "r", &f
);
1327 return log_debug_errno(r
, "Failed to convert file handle: %m");
1329 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1331 return log_debug_errno(r
, "Failed to read from %s/%s: %m", where
, p
);
1333 e
= startswith(line
, PORTABLE_DROPIN_MARKER_BEGIN
);
1337 k
= endswith(e
, PORTABLE_DROPIN_MARKER_END
);
1341 marker
= strndup(e
, k
- e
);
1348 r
= marker_matches_images(marker
, name_or_path
, extension_image_paths
);
1351 *ret_marker
= TAKE_PTR(marker
);
1356 int portable_detach(
1358 const char *name_or_path
,
1359 char **extension_image_paths
,
1360 PortableFlags flags
,
1361 PortableChange
**changes
,
1363 sd_bus_error
*error
) {
1365 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1366 _cleanup_set_free_ Set
*unit_files
= NULL
, *markers
= NULL
;
1367 _cleanup_closedir_
DIR *d
= NULL
;
1368 const char *where
, *item
;
1373 assert(name_or_path
);
1375 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1379 where
= attached_path(&paths
, flags
);
1383 if (errno
== ENOENT
)
1386 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1389 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1390 _cleanup_free_
char *marker
= NULL
;
1391 UnitFileState state
;
1393 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1396 /* Filter out duplicates */
1397 if (set_contains(unit_files
, de
->d_name
))
1400 dirent_ensure_type(d
, de
);
1401 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1404 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, extension_image_paths
, &marker
);
1410 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1412 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1413 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_RUNTIME
, UNIT_FILE_LINKED_RUNTIME
))
1414 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
));
1416 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1419 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1420 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active, can't detach.", de
->d_name
);
1422 r
= set_put_strdup(&unit_files
, de
->d_name
);
1424 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1426 for (const char *p
= marker
;;) {
1427 _cleanup_free_
char *image
= NULL
;
1429 r
= extract_first_word(&p
, &image
, ":", EXTRACT_UNESCAPE_SEPARATORS
|EXTRACT_RETAIN_ESCAPE
);
1431 return log_debug_errno(r
, "Failed to parse marker: %s", p
);
1435 if (path_is_absolute(image
) && !image_in_search_path(IMAGE_PORTABLE
, NULL
, image
)) {
1436 r
= set_ensure_consume(&markers
, &path_hash_ops_free
, TAKE_PTR(image
));
1443 if (set_isempty(unit_files
))
1446 SET_FOREACH(item
, unit_files
) {
1447 _cleanup_free_
char *md
= NULL
;
1450 if (unlinkat(dirfd(d
), item
, 0) < 0) {
1451 log_debug_errno(errno
, "Can't remove unit file %s/%s: %m", where
, item
);
1453 if (errno
!= ENOENT
&& ret
>= 0)
1456 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, item
, NULL
);
1458 FOREACH_STRING(suffix
, ".d/10-profile.conf", ".d/20-portable.conf") {
1459 _cleanup_free_
char *dropin
= NULL
;
1461 dropin
= strjoin(item
, suffix
);
1465 if (unlinkat(dirfd(d
), dropin
, 0) < 0) {
1466 log_debug_errno(errno
, "Can't remove drop-in %s/%s: %m", where
, dropin
);
1468 if (errno
!= ENOENT
&& ret
>= 0)
1471 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, dropin
, NULL
);
1474 md
= strjoin(item
, ".d");
1478 if (unlinkat(dirfd(d
), md
, AT_REMOVEDIR
) < 0) {
1479 log_debug_errno(errno
, "Can't remove drop-in directory %s/%s: %m", where
, md
);
1481 if (errno
!= ENOENT
&& ret
>= 0)
1484 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, md
, NULL
);
1487 /* Now, also drop any image symlink, for images outside of the sarch path */
1488 SET_FOREACH(item
, markers
) {
1489 _cleanup_free_
char *sl
= NULL
;
1492 r
= image_symlink(item
, flags
, &sl
);
1494 log_debug_errno(r
, "Failed to determine image symlink for '%s', ignoring: %m", item
);
1498 if (lstat(sl
, &st
) < 0) {
1499 log_debug_errno(errno
, "Failed to stat '%s', ignoring: %m", sl
);
1503 if (!S_ISLNK(st
.st_mode
)) {
1504 log_debug("Image '%s' is not a symlink, ignoring.", sl
);
1508 if (unlink(sl
) < 0) {
1509 log_debug_errno(errno
, "Can't remove image symlink '%s': %m", sl
);
1511 if (errno
!= ENOENT
&& ret
>= 0)
1514 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, sl
, NULL
);
1517 /* Try to remove the unit file directory, if we can */
1518 if (rmdir(where
) >= 0)
1519 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, where
, NULL
);
1524 log_debug("No unit files associated with '%s' found. Image not attached?", name_or_path
);
1525 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_UNIT
, "No unit files associated with '%s' found. Image not attached?", name_or_path
);
1528 static int portable_get_state_internal(
1530 const char *name_or_path
,
1531 PortableFlags flags
,
1533 sd_bus_error
*error
) {
1535 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1536 bool found_enabled
= false, found_running
= false;
1537 _cleanup_set_free_ Set
*unit_files
= NULL
;
1538 _cleanup_closedir_
DIR *d
= NULL
;
1543 assert(name_or_path
);
1546 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1550 where
= attached_path(&paths
, flags
);
1554 if (errno
== ENOENT
) {
1555 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1556 *ret
= PORTABLE_DETACHED
;
1560 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1563 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1564 UnitFileState state
;
1566 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1569 /* Filter out duplicates */
1570 if (set_contains(unit_files
, de
->d_name
))
1573 dirent_ensure_type(d
, de
);
1574 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1577 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, NULL
, NULL
);
1583 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1585 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1586 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_LINKED_RUNTIME
))
1587 found_enabled
= true;
1589 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1593 found_running
= true;
1595 r
= set_put_strdup(&unit_files
, de
->d_name
);
1597 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1600 *ret
= found_running
? (!set_isempty(unit_files
) && (flags
& PORTABLE_RUNTIME
) ? PORTABLE_RUNNING_RUNTIME
: PORTABLE_RUNNING
) :
1601 found_enabled
? (flags
& PORTABLE_RUNTIME
? PORTABLE_ENABLED_RUNTIME
: PORTABLE_ENABLED
) :
1602 !set_isempty(unit_files
) ? (flags
& PORTABLE_RUNTIME
? PORTABLE_ATTACHED_RUNTIME
: PORTABLE_ATTACHED
) : PORTABLE_DETACHED
;
1607 int portable_get_state(
1609 const char *name_or_path
,
1610 PortableFlags flags
,
1612 sd_bus_error
*error
) {
1614 PortableState state
;
1617 assert(name_or_path
);
1620 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1621 * the latter only if we didn't find anything in the former. */
1623 r
= portable_get_state_internal(bus
, name_or_path
, flags
& ~PORTABLE_RUNTIME
, &state
, error
);
1627 if (state
== PORTABLE_DETACHED
) {
1628 r
= portable_get_state_internal(bus
, name_or_path
, flags
| PORTABLE_RUNTIME
, &state
, error
);
1637 int portable_get_profiles(char ***ret
) {
1640 return conf_files_list_nulstr(ret
, NULL
, NULL
, CONF_FILES_DIRECTORY
|CONF_FILES_BASENAME
|CONF_FILES_FILTER_MASKED
, profile_dirs
);
1643 static const char* const portable_change_type_table
[_PORTABLE_CHANGE_TYPE_MAX
] = {
1644 [PORTABLE_COPY
] = "copy",
1645 [PORTABLE_MKDIR
] = "mkdir",
1646 [PORTABLE_SYMLINK
] = "symlink",
1647 [PORTABLE_UNLINK
] = "unlink",
1648 [PORTABLE_WRITE
] = "write",
1651 DEFINE_STRING_TABLE_LOOKUP(portable_change_type
, int);
1653 static const char* const portable_state_table
[_PORTABLE_STATE_MAX
] = {
1654 [PORTABLE_DETACHED
] = "detached",
1655 [PORTABLE_ATTACHED
] = "attached",
1656 [PORTABLE_ATTACHED_RUNTIME
] = "attached-runtime",
1657 [PORTABLE_ENABLED
] = "enabled",
1658 [PORTABLE_ENABLED_RUNTIME
] = "enabled-runtime",
1659 [PORTABLE_RUNNING
] = "running",
1660 [PORTABLE_RUNNING_RUNTIME
] = "running-runtime",
1663 DEFINE_STRING_TABLE_LOOKUP(portable_state
, PortableState
);