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");
396 d
->uevent_seqnum_not_before
,
397 d
->timestamp_not_before
,
398 DISSECT_IMAGE_READ_ONLY
|
399 DISSECT_IMAGE_GENERIC_ROOT
|
400 DISSECT_IMAGE_REQUIRE_ROOT
|
401 DISSECT_IMAGE_DISCARD_ON_LOOP
|
402 DISSECT_IMAGE_RELAX_VAR_CHECK
|
403 DISSECT_IMAGE_USR_NO_ROOT
,
406 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't identify a suitable partition table or file system in '%s'.", path
);
407 else if (r
== -EADDRNOTAVAIL
)
408 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No root partition for specified root hash found in '%s'.", path
);
409 else if (r
== -ENOTUNIQ
)
410 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Multiple suitable root partitions found in image '%s'.", path
);
411 else if (r
== -ENXIO
)
412 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No suitable root partition found in image '%s'.", path
);
413 else if (r
== -EPROTONOSUPPORT
)
414 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
);
418 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, seq
) < 0)
419 return log_debug_errno(errno
, "Failed to allocated SOCK_SEQPACKET socket: %m");
421 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
|FORK_LOG
, &child
);
425 seq
[0] = safe_close(seq
[0]);
427 r
= dissected_image_mount(m
, tmpdir
, UID_INVALID
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
);
429 log_debug_errno(r
, "Failed to mount dissected image: %m");
433 r
= extract_now(tmpdir
, matches
, seq
[1], NULL
, NULL
);
436 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
439 seq
[1] = safe_close(seq
[1]);
441 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
446 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*add
= NULL
;
447 _cleanup_free_
char *name
= NULL
;
448 _cleanup_close_
int fd
= -1;
450 r
= recv_item(seq
[0], &name
, &fd
);
452 return log_debug_errno(r
, "Failed to receive item: %m");
454 /* We can't really distinguish a zero-length datagram without any fds from EOF (both are signalled the
455 * same way by recvmsg()). Hence, accept either as end notification. */
456 if (isempty(name
) && fd
< 0)
459 if (isempty(name
) || fd
< 0)
460 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
461 "Invalid item sent from child.");
463 add
= portable_metadata_new(name
, path
, fd
);
468 /* Note that we do not initialize 'add->source' here, as the source path is not usable here as
469 * it refers to a path only valid in the short-living namespaced child process we forked
472 if (PORTABLE_METADATA_IS_UNIT(add
)) {
473 r
= hashmap_put(unit_files
, add
->name
, add
);
475 return log_debug_errno(r
, "Failed to add item to unit file list: %m");
479 } else if (PORTABLE_METADATA_IS_OS_RELEASE(add
)) {
482 os_release
= TAKE_PTR(add
);
484 assert_not_reached("Unexpected metadata item from child.");
487 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
493 /* When the portable image is layered, the image with units will not
494 * have a full filesystem, so no os-release - it will be in the root layer */
495 if (extract_os_release
&& !os_release
)
496 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Image '%s' lacks os-release data, refusing.", path
);
498 if (!extract_os_release
&& hashmap_isempty(unit_files
))
499 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't find any matching unit files in image '%s', refusing.", path
);
502 *ret_unit_files
= TAKE_PTR(unit_files
);
505 *ret_os_release
= TAKE_PTR(os_release
);
510 int portable_extract(
511 const char *name_or_path
,
513 char **extension_image_paths
,
514 PortableMetadata
**ret_os_release
,
515 Hashmap
**ret_unit_files
,
516 sd_bus_error
*error
) {
518 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
519 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
;
520 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
521 _cleanup_(image_unrefp
) Image
*image
= NULL
;
525 assert(name_or_path
);
527 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, NULL
, &image
);
531 if (!strv_isempty(extension_image_paths
)) {
534 extension_images
= ordered_hashmap_new(&image_hash_ops
);
535 if (!extension_images
)
538 STRV_FOREACH(p
, extension_image_paths
) {
539 _cleanup_(image_unrefp
) Image
*new = NULL
;
541 r
= image_find_harder(IMAGE_PORTABLE
, *p
, NULL
, &new);
545 r
= ordered_hashmap_put(extension_images
, new->name
, new);
552 r
= portable_extract_by_path(image
->path
, true, matches
, &os_release
, &unit_files
, error
);
556 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
557 _cleanup_hashmap_free_ Hashmap
*extra_unit_files
= NULL
;
559 r
= portable_extract_by_path(ext
->path
, false, matches
, NULL
, &extra_unit_files
, error
);
562 r
= hashmap_move(unit_files
, extra_unit_files
);
567 *ret_os_release
= TAKE_PTR(os_release
);
568 *ret_unit_files
= TAKE_PTR(unit_files
);
573 static int unit_file_is_active(
576 sd_bus_error
*error
) {
578 static const char *const active_states
[] = {
590 /* If we are looking at a plain or instance things are easy, we can just query the state */
591 if (unit_name_is_valid(name
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
)) {
592 _cleanup_free_
char *path
= NULL
, *buf
= NULL
;
594 path
= unit_dbus_path_from_name(name
);
598 r
= sd_bus_get_property_string(
600 "org.freedesktop.systemd1",
602 "org.freedesktop.systemd1.Unit",
607 return log_debug_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(error
, r
));
609 return strv_contains((char**) active_states
, buf
);
612 /* Otherwise we need to enumerate. But let's build the most restricted query we can */
613 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
614 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
615 const char *at
, *prefix
, *joined
;
617 r
= sd_bus_message_new_method_call(
620 "org.freedesktop.systemd1",
621 "/org/freedesktop/systemd1",
622 "org.freedesktop.systemd1.Manager",
623 "ListUnitsByPatterns");
627 r
= sd_bus_message_append_strv(m
, (char**) active_states
);
631 at
= strchr(name
, '@');
634 prefix
= strndupa(name
, at
+ 1 - name
);
635 joined
= strjoina(prefix
, "*", at
+ 1);
637 r
= sd_bus_message_append_strv(m
, STRV_MAKE(joined
));
641 r
= sd_bus_call(bus
, m
, 0, error
, &reply
);
643 return log_debug_errno(r
, "Failed to list units: %s", bus_error_message(error
, r
));
645 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
649 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_STRUCT
, "ssssssouso");
659 static int portable_changes_add(
660 PortableChange
**changes
,
662 int type_or_errno
, /* PORTABLE_COPY, PORTABLE_SYMLINK, … if positive, or errno if negative */
664 const char *source
) {
666 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
670 assert(!changes
== !n_changes
);
672 if (type_or_errno
>= 0)
673 assert(type_or_errno
< _PORTABLE_CHANGE_TYPE_MAX
);
675 assert(type_or_errno
>= -ERRNO_MAX
);
680 c
= reallocarray(*changes
, *n_changes
+ 1, sizeof(PortableChange
));
699 c
[(*n_changes
)++] = (PortableChange
) {
700 .type_or_errno
= type_or_errno
,
702 .source
= TAKE_PTR(s
),
708 static int portable_changes_add_with_prefix(
709 PortableChange
**changes
,
714 const char *source
) {
717 assert(!changes
== !n_changes
);
723 path
= prefix_roota(prefix
, path
);
726 source
= prefix_roota(prefix
, source
);
729 return portable_changes_add(changes
, n_changes
, type_or_errno
, path
, source
);
732 void portable_changes_free(PortableChange
*changes
, size_t n_changes
) {
735 assert(changes
|| n_changes
== 0);
737 for (i
= 0; i
< n_changes
; i
++) {
738 free(changes
[i
].path
);
739 free(changes
[i
].source
);
745 static const char *root_setting_from_image(ImageType type
) {
746 return IN_SET(type
, IMAGE_DIRECTORY
, IMAGE_SUBVOLUME
) ? "RootDirectory=" : "RootImage=";
749 static int make_marker_text(const char *image_path
, OrderedHashmap
*extension_images
, char **ret_text
) {
750 _cleanup_free_
char *text
= NULL
, *escaped_image_path
= NULL
;
756 escaped_image_path
= xescape(image_path
, ":");
757 if (!escaped_image_path
)
760 /* If the image is layered, include all layers in the marker as a colon-separated
761 * list of paths, so that we can do exact matches on removal. */
762 text
= strjoin(PORTABLE_DROPIN_MARKER_BEGIN
, escaped_image_path
);
766 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
767 _cleanup_free_
char *escaped
= NULL
;
769 escaped
= xescape(ext
->path
, ":");
773 if (!strextend(&text
, ":", escaped
))
777 if (!strextend(&text
, PORTABLE_DROPIN_MARKER_END
"\n"))
780 *ret_text
= TAKE_PTR(text
);
784 static int install_chroot_dropin(
785 const char *image_path
,
787 OrderedHashmap
*extension_images
,
788 const PortableMetadata
*m
,
789 const char *dropin_dir
,
791 PortableChange
**changes
,
794 _cleanup_free_
char *text
= NULL
, *dropin
= NULL
;
802 dropin
= path_join(dropin_dir
, "20-portable.conf");
806 r
= make_marker_text(image_path
, extension_images
, &text
);
808 return log_debug_errno(r
, "Failed to generate marker string for portable drop-in: %m");
810 if (endswith(m
->name
, ".service")) {
811 const char *os_release_source
, *root_type
;
812 _cleanup_free_
char *base_name
= NULL
;
814 root_type
= root_setting_from_image(type
);
816 if (access("/etc/os-release", F_OK
) < 0) {
818 return log_debug_errno(errno
, "Failed to check if /etc/os-release exists: %m");
820 os_release_source
= "/usr/lib/os-release";
822 os_release_source
= "/etc/os-release";
824 r
= path_extract_filename(m
->image_path
?: image_path
, &base_name
);
826 return log_debug_errno(r
, "Failed to extract basename from '%s': %m", m
->image_path
?: image_path
);
828 if (!strextend(&text
,
831 root_type
, image_path
, "\n"
832 "Environment=PORTABLE=", base_name
, "\n"
833 "BindReadOnlyPaths=", os_release_source
, ":/run/host/os-release\n"
834 "LogExtraFields=PORTABLE=", base_name
, "\n"))
837 if (m
->image_path
&& !path_equal(m
->image_path
, image_path
))
838 ORDERED_HASHMAP_FOREACH(ext
, extension_images
)
839 if (!strextend(&text
, "ExtensionImages=", ext
->path
, "\n"))
843 r
= write_string_file(dropin
, text
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
845 return log_debug_errno(r
, "Failed to write '%s': %m", dropin
);
847 (void) portable_changes_add(changes
, n_changes
, PORTABLE_WRITE
, dropin
, NULL
);
850 *ret_dropin
= TAKE_PTR(dropin
);
855 static int find_profile(const char *name
, const char *unit
, char **ret
) {
861 assert_se(dot
= strrchr(unit
, '.'));
863 NULSTR_FOREACH(p
, profile_dirs
) {
864 _cleanup_free_
char *joined
= NULL
;
866 joined
= strjoin(p
, "/", name
, "/", dot
+ 1, ".conf");
870 if (laccess(joined
, F_OK
) >= 0) {
871 *ret
= TAKE_PTR(joined
);
882 static int install_profile_dropin(
883 const char *image_path
,
884 const PortableMetadata
*m
,
885 const char *dropin_dir
,
889 PortableChange
**changes
,
892 _cleanup_free_
char *dropin
= NULL
, *from
= NULL
;
902 r
= find_profile(profile
, m
->name
, &from
);
905 return log_debug_errno(errno
, "Profile '%s' is not accessible: %m", profile
);
907 log_debug_errno(errno
, "Skipping link to profile '%s', as it does not exist: %m", profile
);
911 dropin
= path_join(dropin_dir
, "10-profile.conf");
915 if (flags
& PORTABLE_PREFER_COPY
) {
917 r
= copy_file_atomic(from
, dropin
, 0644, 0, 0, COPY_REFLINK
);
919 return log_debug_errno(r
, "Failed to copy %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW
), dropin
);
921 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, dropin
, from
);
925 if (symlink(from
, dropin
) < 0)
926 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW
), dropin
);
928 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, dropin
, from
);
932 *ret_dropin
= TAKE_PTR(dropin
);
937 static const char *attached_path(const LookupPaths
*paths
, PortableFlags flags
) {
942 if (flags
& PORTABLE_RUNTIME
)
943 where
= paths
->runtime_attached
;
945 where
= paths
->persistent_attached
;
951 static int attach_unit_file(
952 const LookupPaths
*paths
,
953 const char *image_path
,
955 OrderedHashmap
*extension_images
,
956 const PortableMetadata
*m
,
959 PortableChange
**changes
,
962 _cleanup_(unlink_and_freep
) char *chroot_dropin
= NULL
, *profile_dropin
= NULL
;
963 _cleanup_(rmdir_and_freep
) char *dropin_dir
= NULL
;
964 const char *where
, *path
;
970 assert(PORTABLE_METADATA_IS_UNIT(m
));
972 where
= attached_path(paths
, flags
);
974 (void) mkdir_parents(where
, 0755);
975 if (mkdir(where
, 0755) < 0) {
979 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, where
, NULL
);
981 path
= prefix_roota(where
, m
->name
);
982 dropin_dir
= strjoin(path
, ".d");
986 if (mkdir(dropin_dir
, 0755) < 0) {
990 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, dropin_dir
, NULL
);
992 /* We install the drop-ins first, and the actual unit file last to achieve somewhat atomic behaviour if PID 1
993 * is reloaded while we are creating things here: as long as only the drop-ins exist the unit doesn't exist at
996 r
= install_chroot_dropin(image_path
, type
, extension_images
, m
, dropin_dir
, &chroot_dropin
, changes
, n_changes
);
1000 r
= install_profile_dropin(image_path
, m
, dropin_dir
, profile
, flags
, &profile_dropin
, changes
, n_changes
);
1004 if ((flags
& PORTABLE_PREFER_SYMLINK
) && m
->source
) {
1006 if (symlink(m
->source
, path
) < 0)
1007 return log_debug_errno(errno
, "Failed to symlink unit file '%s': %m", path
);
1009 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, path
, m
->source
);
1012 _cleanup_(unlink_and_freep
) char *tmp
= NULL
;
1013 _cleanup_close_
int fd
= -1;
1015 fd
= open_tmpfile_linkable(path
, O_WRONLY
|O_CLOEXEC
, &tmp
);
1017 return log_debug_errno(fd
, "Failed to create unit file '%s': %m", path
);
1019 r
= copy_bytes(m
->fd
, fd
, UINT64_MAX
, COPY_REFLINK
);
1021 return log_debug_errno(r
, "Failed to copy unit file '%s': %m", path
);
1023 if (fchmod(fd
, 0644) < 0)
1024 return log_debug_errno(errno
, "Failed to change unit file access mode for '%s': %m", path
);
1026 r
= link_tmpfile(fd
, tmp
, path
);
1028 return log_debug_errno(r
, "Failed to install unit file '%s': %m", path
);
1032 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, path
, m
->source
);
1035 /* All is established now, now let's disable any rollbacks */
1036 chroot_dropin
= mfree(chroot_dropin
);
1037 profile_dropin
= mfree(profile_dropin
);
1038 dropin_dir
= mfree(dropin_dir
);
1043 static int image_symlink(
1044 const char *image_path
,
1045 PortableFlags flags
,
1048 const char *fn
, *where
;
1049 char *joined
= NULL
;
1054 fn
= last_path_component(image_path
);
1056 if (flags
& PORTABLE_RUNTIME
)
1057 where
= "/run/portables/";
1059 where
= "/etc/portables/";
1061 joined
= strjoin(where
, fn
);
1069 static int install_image_symlink(
1070 const char *image_path
,
1071 PortableFlags flags
,
1072 PortableChange
**changes
,
1073 size_t *n_changes
) {
1075 _cleanup_free_
char *sl
= NULL
;
1080 /* If the image is outside of the image search also link it into it, so that it can be found with short image
1081 * names and is listed among the images. */
1083 if (image_in_search_path(IMAGE_PORTABLE
, NULL
, image_path
))
1086 r
= image_symlink(image_path
, flags
, &sl
);
1088 return log_debug_errno(r
, "Failed to generate image symlink path: %m");
1090 (void) mkdir_parents(sl
, 0755);
1092 if (symlink(image_path
, sl
) < 0)
1093 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", image_path
, special_glyph(SPECIAL_GLYPH_ARROW
), sl
);
1095 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, sl
, image_path
);
1099 static int install_image_and_extensions_symlinks(
1101 OrderedHashmap
*extension_images
,
1102 PortableFlags flags
,
1103 PortableChange
**changes
,
1104 size_t *n_changes
) {
1111 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
1112 r
= install_image_symlink(ext
->path
, flags
, changes
, n_changes
);
1117 r
= install_image_symlink(image
->path
, flags
, changes
, n_changes
);
1124 int portable_attach(
1126 const char *name_or_path
,
1128 const char *profile
,
1129 char **extension_image_paths
,
1130 PortableFlags flags
,
1131 PortableChange
**changes
,
1133 sd_bus_error
*error
) {
1135 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
;
1136 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
1137 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1138 _cleanup_(image_unrefp
) Image
*image
= NULL
;
1139 PortableMetadata
*item
;
1144 assert(name_or_path
);
1146 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, NULL
, &image
);
1149 if (!strv_isempty(extension_image_paths
)) {
1150 extension_images
= ordered_hashmap_new(&image_hash_ops
);
1151 if (!extension_images
)
1154 STRV_FOREACH(p
, extension_image_paths
) {
1155 _cleanup_(image_unrefp
) Image
*new = NULL
;
1157 r
= image_find_harder(IMAGE_PORTABLE
, *p
, NULL
, &new);
1161 r
= ordered_hashmap_put(extension_images
, new->name
, new);
1168 r
= portable_extract_by_path(image
->path
, true, matches
, NULL
, &unit_files
, error
);
1172 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
1173 _cleanup_hashmap_free_ Hashmap
*extra_unit_files
= NULL
;
1175 r
= portable_extract_by_path(ext
->path
, false, matches
, NULL
, &extra_unit_files
, error
);
1178 r
= hashmap_move(unit_files
, extra_unit_files
);
1183 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1187 HASHMAP_FOREACH(item
, unit_files
) {
1188 r
= unit_file_exists(UNIT_FILE_SYSTEM
, &paths
, item
->name
);
1190 return sd_bus_error_set_errnof(error
, r
, "Failed to determine whether unit '%s' exists on the host: %m", item
->name
);
1191 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1192 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' exists on the host already, refusing.", item
->name
);
1194 r
= unit_file_is_active(bus
, item
->name
, error
);
1197 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1198 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active already, refusing.", item
->name
);
1201 HASHMAP_FOREACH(item
, unit_files
) {
1202 r
= attach_unit_file(&paths
, image
->path
, image
->type
, extension_images
,
1203 item
, profile
, flags
, changes
, n_changes
);
1208 /* We don't care too much for the image symlink, it's just a convenience thing, it's not necessary for proper
1209 * operation otherwise. */
1210 (void) install_image_and_extensions_symlinks(image
, extension_images
, flags
, changes
, n_changes
);
1215 static bool marker_matches_images(const char *marker
, const char *name_or_path
, char **extension_image_paths
) {
1216 _cleanup_strv_free_
char **root_and_extensions
= NULL
;
1217 char **image_name_or_path
;
1222 assert(name_or_path
);
1224 /* If extensions were used when attaching, the marker will be a colon-separated
1225 * list of images/paths. We enforce strict 1:1 matching, so that we are sure
1226 * we are detaching exactly what was attached.
1227 * For each image, starting with the root, we look for a token in the marker,
1228 * and return a negative answer on any non-matching combination. */
1230 root_and_extensions
= strv_new(name_or_path
);
1231 if (!root_and_extensions
)
1234 r
= strv_extend_strv(&root_and_extensions
, extension_image_paths
, false);
1238 STRV_FOREACH(image_name_or_path
, root_and_extensions
) {
1239 _cleanup_free_
char *image
= NULL
;
1241 r
= extract_first_word(&marker
, &image
, ":", EXTRACT_UNQUOTE
|EXTRACT_RETAIN_ESCAPE
);
1243 return log_debug_errno(r
, "Failed to parse marker: %s", marker
);
1247 a
= last_path_component(image
);
1249 if (image_name_is_valid(*image_name_or_path
)) {
1250 const char *e
, *underscore
;
1252 /* We shall match against an image name. In that case let's compare the last component, and optionally
1253 * allow either a suffix of ".raw" or a series of "/".
1254 * But allow matching on a different version of the same image, when a "_" is used as a separator. */
1255 underscore
= strchr(*image_name_or_path
, '_');
1257 if (strneq(a
, *image_name_or_path
, underscore
- *image_name_or_path
))
1262 e
= startswith(a
, *image_name_or_path
);
1266 if(!(e
[strspn(e
, "/")] == 0 || streq(e
, ".raw")))
1269 const char *b
, *underscore
;
1272 /* We shall match against a path. Let's ignore any prefix here though, as often there are many ways to
1273 * reach the same file. However, in this mode, let's validate any file suffix. */
1275 l
= strcspn(a
, "/");
1276 b
= last_path_component(*image_name_or_path
);
1278 if (strcspn(b
, "/") != l
)
1281 underscore
= strchr(b
, '_');
1285 if (!strneq(a
, b
, l
))
1293 static int test_chroot_dropin(
1297 const char *name_or_path
,
1298 char **extension_image_paths
,
1299 char **ret_marker
) {
1301 _cleanup_free_
char *line
= NULL
, *marker
= NULL
;
1302 _cleanup_fclose_
FILE *f
= NULL
;
1303 _cleanup_close_
int fd
= -1;
1304 const char *p
, *e
, *k
;
1311 /* We recognize unis created from portable images via the drop-in we created for them */
1313 p
= strjoina(fname
, ".d/20-portable.conf");
1314 fd
= openat(dirfd(d
), p
, O_RDONLY
|O_CLOEXEC
);
1316 if (errno
== ENOENT
)
1319 return log_debug_errno(errno
, "Failed to open %s/%s: %m", where
, p
);
1322 r
= take_fdopen_unlocked(&fd
, "r", &f
);
1324 return log_debug_errno(r
, "Failed to convert file handle: %m");
1326 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1328 return log_debug_errno(r
, "Failed to read from %s/%s: %m", where
, p
);
1330 e
= startswith(line
, PORTABLE_DROPIN_MARKER_BEGIN
);
1334 k
= endswith(e
, PORTABLE_DROPIN_MARKER_END
);
1338 marker
= strndup(e
, k
- e
);
1345 r
= marker_matches_images(marker
, name_or_path
, extension_image_paths
);
1348 *ret_marker
= TAKE_PTR(marker
);
1353 int portable_detach(
1355 const char *name_or_path
,
1356 char **extension_image_paths
,
1357 PortableFlags flags
,
1358 PortableChange
**changes
,
1360 sd_bus_error
*error
) {
1362 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1363 _cleanup_set_free_ Set
*unit_files
= NULL
, *markers
= NULL
;
1364 _cleanup_closedir_
DIR *d
= NULL
;
1365 const char *where
, *item
;
1370 assert(name_or_path
);
1372 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1376 where
= attached_path(&paths
, flags
);
1380 if (errno
== ENOENT
)
1383 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1386 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1387 _cleanup_free_
char *marker
= NULL
;
1388 UnitFileState state
;
1390 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1393 /* Filter out duplicates */
1394 if (set_contains(unit_files
, de
->d_name
))
1397 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1400 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, extension_image_paths
, &marker
);
1406 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1408 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1409 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_RUNTIME
, UNIT_FILE_LINKED_RUNTIME
))
1410 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
));
1412 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1415 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1416 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active, can't detach.", de
->d_name
);
1418 r
= set_put_strdup(&unit_files
, de
->d_name
);
1420 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1422 for (const char *p
= marker
;;) {
1423 _cleanup_free_
char *image
= NULL
;
1425 r
= extract_first_word(&p
, &image
, ":", EXTRACT_UNESCAPE_SEPARATORS
|EXTRACT_RETAIN_ESCAPE
);
1427 return log_debug_errno(r
, "Failed to parse marker: %s", p
);
1431 if (path_is_absolute(image
) && !image_in_search_path(IMAGE_PORTABLE
, NULL
, image
)) {
1432 r
= set_ensure_consume(&markers
, &path_hash_ops_free
, TAKE_PTR(image
));
1439 if (set_isempty(unit_files
))
1442 SET_FOREACH(item
, unit_files
) {
1443 _cleanup_free_
char *md
= NULL
;
1446 if (unlinkat(dirfd(d
), item
, 0) < 0) {
1447 log_debug_errno(errno
, "Can't remove unit file %s/%s: %m", where
, item
);
1449 if (errno
!= ENOENT
&& ret
>= 0)
1452 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, item
, NULL
);
1454 FOREACH_STRING(suffix
, ".d/10-profile.conf", ".d/20-portable.conf") {
1455 _cleanup_free_
char *dropin
= NULL
;
1457 dropin
= strjoin(item
, suffix
);
1461 if (unlinkat(dirfd(d
), dropin
, 0) < 0) {
1462 log_debug_errno(errno
, "Can't remove drop-in %s/%s: %m", where
, dropin
);
1464 if (errno
!= ENOENT
&& ret
>= 0)
1467 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, dropin
, NULL
);
1470 md
= strjoin(item
, ".d");
1474 if (unlinkat(dirfd(d
), md
, AT_REMOVEDIR
) < 0) {
1475 log_debug_errno(errno
, "Can't remove drop-in directory %s/%s: %m", where
, md
);
1477 if (errno
!= ENOENT
&& ret
>= 0)
1480 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, md
, NULL
);
1483 /* Now, also drop any image symlink, for images outside of the sarch path */
1484 SET_FOREACH(item
, markers
) {
1485 _cleanup_free_
char *sl
= NULL
;
1488 r
= image_symlink(item
, flags
, &sl
);
1490 log_debug_errno(r
, "Failed to determine image symlink for '%s', ignoring: %m", item
);
1494 if (lstat(sl
, &st
) < 0) {
1495 log_debug_errno(errno
, "Failed to stat '%s', ignoring: %m", sl
);
1499 if (!S_ISLNK(st
.st_mode
)) {
1500 log_debug("Image '%s' is not a symlink, ignoring.", sl
);
1504 if (unlink(sl
) < 0) {
1505 log_debug_errno(errno
, "Can't remove image symlink '%s': %m", sl
);
1507 if (errno
!= ENOENT
&& ret
>= 0)
1510 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, sl
, NULL
);
1513 /* Try to remove the unit file directory, if we can */
1514 if (rmdir(where
) >= 0)
1515 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, where
, NULL
);
1520 log_debug("No unit files associated with '%s' found. Image not attached?", name_or_path
);
1521 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_UNIT
, "No unit files associated with '%s' found. Image not attached?", name_or_path
);
1524 static int portable_get_state_internal(
1526 const char *name_or_path
,
1527 PortableFlags flags
,
1529 sd_bus_error
*error
) {
1531 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1532 bool found_enabled
= false, found_running
= false;
1533 _cleanup_set_free_ Set
*unit_files
= NULL
;
1534 _cleanup_closedir_
DIR *d
= NULL
;
1539 assert(name_or_path
);
1542 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1546 where
= attached_path(&paths
, flags
);
1550 if (errno
== ENOENT
) {
1551 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1552 *ret
= PORTABLE_DETACHED
;
1556 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1559 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1560 UnitFileState state
;
1562 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1565 /* Filter out duplicates */
1566 if (set_contains(unit_files
, de
->d_name
))
1569 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1572 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, NULL
, NULL
);
1578 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1580 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1581 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_LINKED_RUNTIME
))
1582 found_enabled
= true;
1584 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1588 found_running
= true;
1590 r
= set_put_strdup(&unit_files
, de
->d_name
);
1592 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1595 *ret
= found_running
? (!set_isempty(unit_files
) && (flags
& PORTABLE_RUNTIME
) ? PORTABLE_RUNNING_RUNTIME
: PORTABLE_RUNNING
) :
1596 found_enabled
? (flags
& PORTABLE_RUNTIME
? PORTABLE_ENABLED_RUNTIME
: PORTABLE_ENABLED
) :
1597 !set_isempty(unit_files
) ? (flags
& PORTABLE_RUNTIME
? PORTABLE_ATTACHED_RUNTIME
: PORTABLE_ATTACHED
) : PORTABLE_DETACHED
;
1602 int portable_get_state(
1604 const char *name_or_path
,
1605 PortableFlags flags
,
1607 sd_bus_error
*error
) {
1609 PortableState state
;
1612 assert(name_or_path
);
1615 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1616 * the latter only if we didn't find anything in the former. */
1618 r
= portable_get_state_internal(bus
, name_or_path
, flags
& ~PORTABLE_RUNTIME
, &state
, error
);
1622 if (state
== PORTABLE_DETACHED
) {
1623 r
= portable_get_state_internal(bus
, name_or_path
, flags
| PORTABLE_RUNTIME
, &state
, error
);
1632 int portable_get_profiles(char ***ret
) {
1635 return conf_files_list_nulstr(ret
, NULL
, NULL
, CONF_FILES_DIRECTORY
|CONF_FILES_BASENAME
|CONF_FILES_FILTER_MASKED
, profile_dirs
);
1638 static const char* const portable_change_type_table
[_PORTABLE_CHANGE_TYPE_MAX
] = {
1639 [PORTABLE_COPY
] = "copy",
1640 [PORTABLE_MKDIR
] = "mkdir",
1641 [PORTABLE_SYMLINK
] = "symlink",
1642 [PORTABLE_UNLINK
] = "unlink",
1643 [PORTABLE_WRITE
] = "write",
1646 DEFINE_STRING_TABLE_LOOKUP(portable_change_type
, int);
1648 static const char* const portable_state_table
[_PORTABLE_STATE_MAX
] = {
1649 [PORTABLE_DETACHED
] = "detached",
1650 [PORTABLE_ATTACHED
] = "attached",
1651 [PORTABLE_ATTACHED_RUNTIME
] = "attached-runtime",
1652 [PORTABLE_ENABLED
] = "enabled",
1653 [PORTABLE_ENABLED_RUNTIME
] = "enabled-runtime",
1654 [PORTABLE_RUNNING
] = "running",
1655 [PORTABLE_RUNNING_RUNTIME
] = "running-runtime",
1658 DEFINE_STRING_TABLE_LOOKUP(portable_state
, PortableState
);