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"
10 #include "dirent-util.h"
11 #include "discover-image.h"
12 #include "dissect-image.h"
13 #include "errno-list.h"
20 #include "locale-util.h"
21 #include "loop-util.h"
23 #include "nulstr-util.h"
25 #include "path-lookup.h"
27 #include "process-util.h"
29 #include "signal-util.h"
30 #include "socket-util.h"
31 #include "sort-util.h"
32 #include "string-table.h"
34 #include "tmpfile-util.h"
35 #include "user-util.h"
37 static const char profile_dirs
[] = CONF_PATHS_NULSTR("systemd/portable/profile");
39 /* Markers used in the first line of our 20-portable.conf unit file drop-in to determine, that a) the unit file was
40 * dropped there by the portable service logic and b) for which image it was dropped there. */
41 #define PORTABLE_DROPIN_MARKER_BEGIN "# Drop-in created for image '"
42 #define PORTABLE_DROPIN_MARKER_END "', do not edit."
44 static bool prefix_match(const char *unit
, const char *prefix
) {
47 p
= startswith(unit
, prefix
);
51 /* Only respect prefixes followed by dash or dot or when there's a complete match */
52 return IN_SET(*p
, '-', '.', '@', 0);
55 static bool unit_match(const char *unit
, char **matches
) {
59 dot
= strrchr(unit
, '.');
63 if (!STR_IN_SET(dot
, ".service", ".socket", ".target", ".timer", ".path"))
66 /* Empty match expression means: everything */
67 if (strv_isempty(matches
))
70 /* Otherwise, at least one needs to match */
71 STRV_FOREACH(i
, matches
)
72 if (prefix_match(unit
, *i
))
78 static PortableMetadata
*portable_metadata_new(const char *name
, const char *path
, int fd
) {
81 m
= malloc0(offsetof(PortableMetadata
, name
) + strlen(name
) + 1);
85 /* In case of a layered attach, we want to remember which image the unit came from */
87 m
->image_path
= strdup(path
);
94 strcpy(m
->name
, name
);
100 PortableMetadata
*portable_metadata_unref(PortableMetadata
*i
) {
111 static int compare_metadata(PortableMetadata
*const *x
, PortableMetadata
*const *y
) {
112 return strcmp((*x
)->name
, (*y
)->name
);
115 int portable_metadata_hashmap_to_sorted_array(Hashmap
*unit_files
, PortableMetadata
***ret
) {
117 _cleanup_free_ PortableMetadata
**sorted
= NULL
;
118 PortableMetadata
*item
;
121 sorted
= new(PortableMetadata
*, hashmap_size(unit_files
));
125 HASHMAP_FOREACH(item
, unit_files
)
128 assert(k
== hashmap_size(unit_files
));
130 typesafe_qsort(sorted
, k
, compare_metadata
);
132 *ret
= TAKE_PTR(sorted
);
136 static int send_item(
141 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
= {};
144 .msg_control
= &control
,
145 .msg_controllen
= sizeof(control
),
149 struct cmsghdr
*cmsg
;
150 _cleanup_close_
int data_fd
= -1;
152 assert(socket_fd
>= 0);
156 data_fd
= fd_duplicate_data_fd(fd
);
160 cmsg
= CMSG_FIRSTHDR(&mh
);
161 cmsg
->cmsg_level
= SOL_SOCKET
;
162 cmsg
->cmsg_type
= SCM_RIGHTS
;
163 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
164 memcpy(CMSG_DATA(cmsg
), &data_fd
, sizeof(int));
166 iovec
= IOVEC_MAKE_STRING(name
);
168 if (sendmsg(socket_fd
, &mh
, MSG_NOSIGNAL
) < 0)
174 static int recv_item(
179 CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control
;
180 char buffer
[PATH_MAX
+2];
181 struct iovec iov
= IOVEC_INIT(buffer
, sizeof(buffer
)-1);
183 .msg_control
= &control
,
184 .msg_controllen
= sizeof(control
),
188 struct cmsghdr
*cmsg
;
189 _cleanup_close_
int found_fd
= -1;
193 assert(socket_fd
>= 0);
197 n
= recvmsg_safe(socket_fd
, &mh
, MSG_CMSG_CLOEXEC
);
201 CMSG_FOREACH(cmsg
, &mh
) {
202 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
203 cmsg
->cmsg_type
== SCM_RIGHTS
) {
205 if (cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
206 assert(found_fd
< 0);
207 found_fd
= *(int*) CMSG_DATA(cmsg
);
218 copy
= strdup(buffer
);
223 *ret_fd
= TAKE_FD(found_fd
);
228 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(portable_metadata_hash_ops
, char, string_hash_func
, string_compare_func
,
229 PortableMetadata
, portable_metadata_unref
);
231 static int extract_now(
235 PortableMetadata
**ret_os_release
,
236 Hashmap
**ret_unit_files
) {
238 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
239 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
240 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
241 _cleanup_close_
int os_release_fd
= -1;
242 _cleanup_free_
char *os_release_path
= NULL
;
246 /* Extracts the metadata from a directory tree 'where'. Extracts two kinds of information: the /etc/os-release
247 * data, and all unit files matching the specified expression. Note that this function is called in two very
248 * different but also similar contexts. When the tool gets invoked on a directory tree, we'll process it
249 * directly, and in-process, and thus can return the requested data directly, via 'ret_os_release' and
250 * 'ret_unit_files'. However, if the tool is invoked on a raw disk image — which needs to be mounted first — we
251 * are invoked in a child process with private mounts and then need to send the collected data to our
252 * parent. To handle both cases in one call this function also gets a 'socket_fd' parameter, which when >= 0 is
253 * used to send the data to the parent. */
257 /* First, find /etc/os-release and send it upstream (or just save it). */
258 r
= open_os_release(where
, &os_release_path
, &os_release_fd
);
260 log_debug_errno(r
, "Couldn't acquire os-release file, ignoring: %m");
262 if (socket_fd
>= 0) {
263 r
= send_item(socket_fd
, "/etc/os-release", os_release_fd
);
265 return log_debug_errno(r
, "Failed to send os-release file: %m");
268 if (ret_os_release
) {
269 os_release
= portable_metadata_new("/etc/os-release", NULL
, os_release_fd
);
274 os_release
->source
= TAKE_PTR(os_release_path
);
278 /* Then, send unit file data to the parent (or/and add it to the hashmap). For that we use our usual unit
279 * discovery logic. Note that we force looking inside of /lib/systemd/system/ for units too, as we mightbe
280 * compiled for a split-usr system but the image might be a legacy-usr one. */
281 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, where
);
283 return log_debug_errno(r
, "Failed to acquire lookup paths: %m");
285 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
289 STRV_FOREACH(i
, paths
.search_path
) {
290 _cleanup_free_
char *resolved
= NULL
;
291 _cleanup_closedir_
DIR *d
= NULL
;
294 r
= chase_symlinks_and_opendir(*i
, where
, 0, &resolved
, &d
);
296 log_debug_errno(r
, "Failed to open unit path '%s', ignoring: %m", *i
);
300 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to read directory: %m")) {
301 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*m
= NULL
;
302 _cleanup_close_
int fd
= -1;
304 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
307 if (!unit_match(de
->d_name
, matches
))
310 /* Filter out duplicates */
311 if (hashmap_get(unit_files
, de
->d_name
))
314 dirent_ensure_type(d
, de
);
315 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
318 fd
= openat(dirfd(d
), de
->d_name
, O_CLOEXEC
|O_RDONLY
);
320 log_debug_errno(errno
, "Failed to open unit file '%s', ignoring: %m", de
->d_name
);
324 if (socket_fd
>= 0) {
325 r
= send_item(socket_fd
, de
->d_name
, fd
);
327 return log_debug_errno(r
, "Failed to send unit metadata to parent: %m");
330 m
= portable_metadata_new(de
->d_name
, NULL
, fd
);
335 m
->source
= path_join(resolved
, de
->d_name
);
339 r
= hashmap_put(unit_files
, m
->name
, m
);
341 return log_debug_errno(r
, "Failed to add unit to hashmap: %m");
347 *ret_os_release
= TAKE_PTR(os_release
);
349 *ret_unit_files
= TAKE_PTR(unit_files
);
354 static int portable_extract_by_path(
356 bool extract_os_release
,
358 PortableMetadata
**ret_os_release
,
359 Hashmap
**ret_unit_files
,
360 sd_bus_error
*error
) {
362 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
363 _cleanup_(portable_metadata_unrefp
) PortableMetadata
* os_release
= NULL
;
364 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
369 r
= loop_device_make_by_path(path
, O_RDONLY
, LO_FLAGS_PARTSCAN
, &d
);
371 /* We can't turn this into a loop-back block device, and this returns EISDIR? Then this is a directory
372 * tree and not a raw device. It's easy then. */
374 r
= extract_now(path
, matches
, -1, &os_release
, &unit_files
);
379 return log_debug_errno(r
, "Failed to set up loopback device for %s: %m", path
);
381 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
382 _cleanup_(rmdir_and_freep
) char *tmpdir
= NULL
;
383 _cleanup_(close_pairp
) int seq
[2] = { -1, -1 };
384 _cleanup_(sigkill_waitp
) pid_t child
= 0;
386 /* We now have a loopback block device, let's fork off a child in its own mount namespace, mount it
387 * there, and extract the metadata we need. The metadata is sent from the child back to us. */
389 BLOCK_SIGNALS(SIGCHLD
);
391 r
= mkdtemp_malloc("/tmp/inspect-XXXXXX", &tmpdir
);
393 return log_debug_errno(r
, "Failed to create temporary directory: %m");
398 d
->uevent_seqnum_not_before
,
399 d
->timestamp_not_before
,
400 DISSECT_IMAGE_READ_ONLY
|
401 DISSECT_IMAGE_GENERIC_ROOT
|
402 DISSECT_IMAGE_REQUIRE_ROOT
|
403 DISSECT_IMAGE_DISCARD_ON_LOOP
|
404 DISSECT_IMAGE_RELAX_VAR_CHECK
|
405 DISSECT_IMAGE_USR_NO_ROOT
,
408 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't identify a suitable partition table or file system in '%s'.", path
);
409 else if (r
== -EADDRNOTAVAIL
)
410 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No root partition for specified root hash found in '%s'.", path
);
411 else if (r
== -ENOTUNIQ
)
412 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Multiple suitable root partitions found in image '%s'.", path
);
413 else if (r
== -ENXIO
)
414 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No suitable root partition found in image '%s'.", path
);
415 else if (r
== -EPROTONOSUPPORT
)
416 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
);
420 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, seq
) < 0)
421 return log_debug_errno(errno
, "Failed to allocated SOCK_SEQPACKET socket: %m");
423 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
|FORK_LOG
, &child
);
427 seq
[0] = safe_close(seq
[0]);
429 r
= dissected_image_mount(m
, tmpdir
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
);
431 log_debug_errno(r
, "Failed to mount dissected image: %m");
435 r
= extract_now(tmpdir
, matches
, seq
[1], NULL
, NULL
);
438 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
441 seq
[1] = safe_close(seq
[1]);
443 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
448 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*add
= NULL
;
449 _cleanup_free_
char *name
= NULL
;
450 _cleanup_close_
int fd
= -1;
452 r
= recv_item(seq
[0], &name
, &fd
);
454 return log_debug_errno(r
, "Failed to receive item: %m");
456 /* We can't really distinguish a zero-length datagram without any fds from EOF (both are signalled the
457 * same way by recvmsg()). Hence, accept either as end notification. */
458 if (isempty(name
) && fd
< 0)
461 if (isempty(name
) || fd
< 0)
462 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
463 "Invalid item sent from child.");
465 add
= portable_metadata_new(name
, path
, fd
);
470 /* Note that we do not initialize 'add->source' here, as the source path is not usable here as
471 * it refers to a path only valid in the short-living namespaced child process we forked
474 if (PORTABLE_METADATA_IS_UNIT(add
)) {
475 r
= hashmap_put(unit_files
, add
->name
, add
);
477 return log_debug_errno(r
, "Failed to add item to unit file list: %m");
481 } else if (PORTABLE_METADATA_IS_OS_RELEASE(add
)) {
484 os_release
= TAKE_PTR(add
);
486 assert_not_reached("Unexpected metadata item from child.");
489 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
495 /* When the portable image is layered, the image with units will not
496 * have a full filesystem, so no os-release - it will be in the root layer */
497 if (extract_os_release
&& !os_release
)
498 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Image '%s' lacks os-release data, refusing.", path
);
500 if (!extract_os_release
&& hashmap_isempty(unit_files
))
501 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't find any matching unit files in image '%s', refusing.", path
);
504 *ret_unit_files
= TAKE_PTR(unit_files
);
507 *ret_os_release
= TAKE_PTR(os_release
);
512 int portable_extract(
513 const char *name_or_path
,
515 char **extension_image_paths
,
516 PortableMetadata
**ret_os_release
,
517 Hashmap
**ret_unit_files
,
518 sd_bus_error
*error
) {
520 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
521 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
;
522 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
523 _cleanup_(image_unrefp
) Image
*image
= NULL
;
527 assert(name_or_path
);
529 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, NULL
, &image
);
533 if (!strv_isempty(extension_image_paths
)) {
536 extension_images
= ordered_hashmap_new(&image_hash_ops
);
537 if (!extension_images
)
540 STRV_FOREACH(p
, extension_image_paths
) {
541 _cleanup_(image_unrefp
) Image
*new = NULL
;
543 r
= image_find_harder(IMAGE_PORTABLE
, *p
, NULL
, &new);
547 r
= ordered_hashmap_put(extension_images
, new->name
, new);
554 r
= portable_extract_by_path(image
->path
, true, matches
, &os_release
, &unit_files
, error
);
558 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
559 _cleanup_hashmap_free_ Hashmap
*extra_unit_files
= NULL
;
561 r
= portable_extract_by_path(ext
->path
, false, matches
, NULL
, &extra_unit_files
, error
);
564 r
= hashmap_move(unit_files
, extra_unit_files
);
569 *ret_os_release
= TAKE_PTR(os_release
);
570 *ret_unit_files
= TAKE_PTR(unit_files
);
575 static int unit_file_is_active(
578 sd_bus_error
*error
) {
580 static const char *const active_states
[] = {
592 /* If we are looking at a plain or instance things are easy, we can just query the state */
593 if (unit_name_is_valid(name
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
)) {
594 _cleanup_free_
char *path
= NULL
, *buf
= NULL
;
596 path
= unit_dbus_path_from_name(name
);
600 r
= sd_bus_get_property_string(
602 "org.freedesktop.systemd1",
604 "org.freedesktop.systemd1.Unit",
609 return log_debug_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(error
, r
));
611 return strv_contains((char**) active_states
, buf
);
614 /* Otherwise we need to enumerate. But let's build the most restricted query we can */
615 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
616 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
617 const char *at
, *prefix
, *joined
;
619 r
= sd_bus_message_new_method_call(
622 "org.freedesktop.systemd1",
623 "/org/freedesktop/systemd1",
624 "org.freedesktop.systemd1.Manager",
625 "ListUnitsByPatterns");
629 r
= sd_bus_message_append_strv(m
, (char**) active_states
);
633 at
= strchr(name
, '@');
636 prefix
= strndupa(name
, at
+ 1 - name
);
637 joined
= strjoina(prefix
, "*", at
+ 1);
639 r
= sd_bus_message_append_strv(m
, STRV_MAKE(joined
));
643 r
= sd_bus_call(bus
, m
, 0, error
, &reply
);
645 return log_debug_errno(r
, "Failed to list units: %s", bus_error_message(error
, r
));
647 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
651 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_STRUCT
, "ssssssouso");
661 static int portable_changes_add(
662 PortableChange
**changes
,
664 int type_or_errno
, /* PORTABLE_COPY, PORTABLE_SYMLINK, … if positive, or errno if negative */
666 const char *source
) {
668 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
672 assert(!changes
== !n_changes
);
674 if (type_or_errno
>= 0)
675 assert(type_or_errno
< _PORTABLE_CHANGE_TYPE_MAX
);
677 assert(type_or_errno
>= -ERRNO_MAX
);
682 c
= reallocarray(*changes
, *n_changes
+ 1, sizeof(PortableChange
));
691 path_simplify(p
, false);
698 path_simplify(s
, false);
701 c
[(*n_changes
)++] = (PortableChange
) {
702 .type_or_errno
= type_or_errno
,
704 .source
= TAKE_PTR(s
),
710 static int portable_changes_add_with_prefix(
711 PortableChange
**changes
,
716 const char *source
) {
719 assert(!changes
== !n_changes
);
725 path
= prefix_roota(prefix
, path
);
728 source
= prefix_roota(prefix
, source
);
731 return portable_changes_add(changes
, n_changes
, type_or_errno
, path
, source
);
734 void portable_changes_free(PortableChange
*changes
, size_t n_changes
) {
737 assert(changes
|| n_changes
== 0);
739 for (i
= 0; i
< n_changes
; i
++) {
740 free(changes
[i
].path
);
741 free(changes
[i
].source
);
747 static const char *root_setting_from_image(ImageType type
) {
748 return IN_SET(type
, IMAGE_DIRECTORY
, IMAGE_SUBVOLUME
) ? "RootDirectory=" : "RootImage=";
751 static int make_marker_text(const char *image_path
, OrderedHashmap
*extension_images
, char **ret_text
) {
752 _cleanup_free_
char *text
= NULL
, *escaped_image_path
= NULL
;
758 escaped_image_path
= xescape(image_path
, ":");
759 if (!escaped_image_path
)
762 /* If the image is layered, include all layers in the marker as a colon-separated
763 * list of paths, so that we can do exact matches on removal. */
764 text
= strjoin(PORTABLE_DROPIN_MARKER_BEGIN
, escaped_image_path
);
768 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
769 _cleanup_free_
char *escaped
= NULL
;
771 escaped
= xescape(ext
->path
, ":");
775 if (!strextend(&text
, ":", escaped
))
779 if (!strextend(&text
, PORTABLE_DROPIN_MARKER_END
"\n"))
782 *ret_text
= TAKE_PTR(text
);
786 static int install_chroot_dropin(
787 const char *image_path
,
789 OrderedHashmap
*extension_images
,
790 const PortableMetadata
*m
,
791 const char *dropin_dir
,
793 PortableChange
**changes
,
796 _cleanup_free_
char *text
= NULL
, *dropin
= NULL
;
804 dropin
= path_join(dropin_dir
, "20-portable.conf");
808 r
= make_marker_text(image_path
, extension_images
, &text
);
810 return log_debug_errno(r
, "Failed to generate marker string for portable drop-in: %m");
812 if (endswith(m
->name
, ".service")) {
813 const char *os_release_source
, *root_type
;
814 _cleanup_free_
char *base_name
= NULL
;
816 root_type
= root_setting_from_image(type
);
818 if (access("/etc/os-release", F_OK
) < 0) {
820 return log_debug_errno(errno
, "Failed to check if /etc/os-release exists: %m");
822 os_release_source
= "/usr/lib/os-release";
824 os_release_source
= "/etc/os-release";
826 r
= path_extract_filename(m
->image_path
?: image_path
, &base_name
);
828 return log_debug_errno(r
, "Failed to extract basename from '%s': %m", m
->image_path
?: image_path
);
830 if (!strextend(&text
,
833 root_type
, image_path
, "\n"
834 "Environment=PORTABLE=", base_name
, "\n"
835 "BindReadOnlyPaths=", os_release_source
, ":/run/host/os-release\n"
836 "LogExtraFields=PORTABLE=", base_name
, "\n"))
839 if (m
->image_path
&& !path_equal(m
->image_path
, image_path
))
840 ORDERED_HASHMAP_FOREACH(ext
, extension_images
)
841 if (!strextend(&text
, "ExtensionImages=", ext
->path
, "\n"))
845 r
= write_string_file(dropin
, text
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
847 return log_debug_errno(r
, "Failed to write '%s': %m", dropin
);
849 (void) portable_changes_add(changes
, n_changes
, PORTABLE_WRITE
, dropin
, NULL
);
852 *ret_dropin
= TAKE_PTR(dropin
);
857 static int find_profile(const char *name
, const char *unit
, char **ret
) {
863 assert_se(dot
= strrchr(unit
, '.'));
865 NULSTR_FOREACH(p
, profile_dirs
) {
866 _cleanup_free_
char *joined
= NULL
;
868 joined
= strjoin(p
, "/", name
, "/", dot
+ 1, ".conf");
872 if (laccess(joined
, F_OK
) >= 0) {
873 *ret
= TAKE_PTR(joined
);
884 static int install_profile_dropin(
885 const char *image_path
,
886 const PortableMetadata
*m
,
887 const char *dropin_dir
,
891 PortableChange
**changes
,
894 _cleanup_free_
char *dropin
= NULL
, *from
= NULL
;
904 r
= find_profile(profile
, m
->name
, &from
);
907 return log_debug_errno(errno
, "Profile '%s' is not accessible: %m", profile
);
909 log_debug_errno(errno
, "Skipping link to profile '%s', as it does not exist: %m", profile
);
913 dropin
= path_join(dropin_dir
, "10-profile.conf");
917 if (flags
& PORTABLE_PREFER_COPY
) {
919 r
= copy_file_atomic(from
, dropin
, 0644, 0, 0, COPY_REFLINK
);
921 return log_debug_errno(r
, "Failed to copy %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW
), dropin
);
923 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, dropin
, from
);
927 if (symlink(from
, dropin
) < 0)
928 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW
), dropin
);
930 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, dropin
, from
);
934 *ret_dropin
= TAKE_PTR(dropin
);
939 static const char *attached_path(const LookupPaths
*paths
, PortableFlags flags
) {
944 if (flags
& PORTABLE_RUNTIME
)
945 where
= paths
->runtime_attached
;
947 where
= paths
->persistent_attached
;
953 static int attach_unit_file(
954 const LookupPaths
*paths
,
955 const char *image_path
,
957 OrderedHashmap
*extension_images
,
958 const PortableMetadata
*m
,
961 PortableChange
**changes
,
964 _cleanup_(unlink_and_freep
) char *chroot_dropin
= NULL
, *profile_dropin
= NULL
;
965 _cleanup_(rmdir_and_freep
) char *dropin_dir
= NULL
;
966 const char *where
, *path
;
972 assert(PORTABLE_METADATA_IS_UNIT(m
));
974 where
= attached_path(paths
, flags
);
976 (void) mkdir_parents(where
, 0755);
977 if (mkdir(where
, 0755) < 0) {
981 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, where
, NULL
);
983 path
= prefix_roota(where
, m
->name
);
984 dropin_dir
= strjoin(path
, ".d");
988 if (mkdir(dropin_dir
, 0755) < 0) {
992 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, dropin_dir
, NULL
);
994 /* We install the drop-ins first, and the actual unit file last to achieve somewhat atomic behaviour if PID 1
995 * is reloaded while we are creating things here: as long as only the drop-ins exist the unit doesn't exist at
998 r
= install_chroot_dropin(image_path
, type
, extension_images
, m
, dropin_dir
, &chroot_dropin
, changes
, n_changes
);
1002 r
= install_profile_dropin(image_path
, m
, dropin_dir
, profile
, flags
, &profile_dropin
, changes
, n_changes
);
1006 if ((flags
& PORTABLE_PREFER_SYMLINK
) && m
->source
) {
1008 if (symlink(m
->source
, path
) < 0)
1009 return log_debug_errno(errno
, "Failed to symlink unit file '%s': %m", path
);
1011 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, path
, m
->source
);
1014 _cleanup_(unlink_and_freep
) char *tmp
= NULL
;
1015 _cleanup_close_
int fd
= -1;
1017 fd
= open_tmpfile_linkable(path
, O_WRONLY
|O_CLOEXEC
, &tmp
);
1019 return log_debug_errno(fd
, "Failed to create unit file '%s': %m", path
);
1021 r
= copy_bytes(m
->fd
, fd
, UINT64_MAX
, COPY_REFLINK
);
1023 return log_debug_errno(r
, "Failed to copy unit file '%s': %m", path
);
1025 if (fchmod(fd
, 0644) < 0)
1026 return log_debug_errno(errno
, "Failed to change unit file access mode for '%s': %m", path
);
1028 r
= link_tmpfile(fd
, tmp
, path
);
1030 return log_debug_errno(r
, "Failed to install unit file '%s': %m", path
);
1034 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, path
, m
->source
);
1037 /* All is established now, now let's disable any rollbacks */
1038 chroot_dropin
= mfree(chroot_dropin
);
1039 profile_dropin
= mfree(profile_dropin
);
1040 dropin_dir
= mfree(dropin_dir
);
1045 static int image_symlink(
1046 const char *image_path
,
1047 PortableFlags flags
,
1050 const char *fn
, *where
;
1051 char *joined
= NULL
;
1056 fn
= last_path_component(image_path
);
1058 if (flags
& PORTABLE_RUNTIME
)
1059 where
= "/run/portables/";
1061 where
= "/etc/portables/";
1063 joined
= strjoin(where
, fn
);
1071 static int install_image_symlink(
1072 const char *image_path
,
1073 PortableFlags flags
,
1074 PortableChange
**changes
,
1075 size_t *n_changes
) {
1077 _cleanup_free_
char *sl
= NULL
;
1082 /* If the image is outside of the image search also link it into it, so that it can be found with short image
1083 * names and is listed among the images. */
1085 if (image_in_search_path(IMAGE_PORTABLE
, NULL
, image_path
))
1088 r
= image_symlink(image_path
, flags
, &sl
);
1090 return log_debug_errno(r
, "Failed to generate image symlink path: %m");
1092 (void) mkdir_parents(sl
, 0755);
1094 if (symlink(image_path
, sl
) < 0)
1095 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", image_path
, special_glyph(SPECIAL_GLYPH_ARROW
), sl
);
1097 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, sl
, image_path
);
1101 static int install_image_and_extensions_symlinks(
1103 OrderedHashmap
*extension_images
,
1104 PortableFlags flags
,
1105 PortableChange
**changes
,
1106 size_t *n_changes
) {
1113 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
1114 r
= install_image_symlink(ext
->path
, flags
, changes
, n_changes
);
1119 r
= install_image_symlink(image
->path
, flags
, changes
, n_changes
);
1126 int portable_attach(
1128 const char *name_or_path
,
1130 const char *profile
,
1131 char **extension_image_paths
,
1132 PortableFlags flags
,
1133 PortableChange
**changes
,
1135 sd_bus_error
*error
) {
1137 _cleanup_ordered_hashmap_free_ OrderedHashmap
*extension_images
= NULL
;
1138 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
1139 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1140 _cleanup_(image_unrefp
) Image
*image
= NULL
;
1141 PortableMetadata
*item
;
1146 assert(name_or_path
);
1148 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, NULL
, &image
);
1151 if (!strv_isempty(extension_image_paths
)) {
1152 extension_images
= ordered_hashmap_new(&image_hash_ops
);
1153 if (!extension_images
)
1156 STRV_FOREACH(p
, extension_image_paths
) {
1157 _cleanup_(image_unrefp
) Image
*new = NULL
;
1159 r
= image_find_harder(IMAGE_PORTABLE
, *p
, NULL
, &new);
1163 r
= ordered_hashmap_put(extension_images
, new->name
, new);
1170 r
= portable_extract_by_path(image
->path
, true, matches
, NULL
, &unit_files
, error
);
1174 ORDERED_HASHMAP_FOREACH(ext
, extension_images
) {
1175 _cleanup_hashmap_free_ Hashmap
*extra_unit_files
= NULL
;
1177 r
= portable_extract_by_path(ext
->path
, false, matches
, NULL
, &extra_unit_files
, error
);
1180 r
= hashmap_move(unit_files
, extra_unit_files
);
1185 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1189 HASHMAP_FOREACH(item
, unit_files
) {
1190 r
= unit_file_exists(UNIT_FILE_SYSTEM
, &paths
, item
->name
);
1192 return sd_bus_error_set_errnof(error
, r
, "Failed to determine whether unit '%s' exists on the host: %m", item
->name
);
1193 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1194 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' exists on the host already, refusing.", item
->name
);
1196 r
= unit_file_is_active(bus
, item
->name
, error
);
1199 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1200 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active already, refusing.", item
->name
);
1203 HASHMAP_FOREACH(item
, unit_files
) {
1204 r
= attach_unit_file(&paths
, image
->path
, image
->type
, extension_images
,
1205 item
, profile
, flags
, changes
, n_changes
);
1210 /* We don't care too much for the image symlink, it's just a convenience thing, it's not necessary for proper
1211 * operation otherwise. */
1212 (void) install_image_and_extensions_symlinks(image
, extension_images
, flags
, changes
, n_changes
);
1217 static bool marker_matches_images(const char *marker
, const char *name_or_path
, char **extension_image_paths
) {
1218 _cleanup_strv_free_
char **root_and_extensions
= NULL
;
1219 char **image_name_or_path
;
1224 assert(name_or_path
);
1226 /* If extensions were used when attaching, the marker will be a colon-separated
1227 * list of images/paths. We enforce strict 1:1 matching, so that we are sure
1228 * we are detaching exactly what was attached.
1229 * For each image, starting with the root, we look for a token in the marker,
1230 * and return a negative answer on any non-matching combination. */
1232 root_and_extensions
= strv_new(name_or_path
);
1233 if (!root_and_extensions
)
1236 r
= strv_extend_strv(&root_and_extensions
, extension_image_paths
, false);
1240 STRV_FOREACH(image_name_or_path
, root_and_extensions
) {
1241 _cleanup_free_
char *image
= NULL
;
1243 r
= extract_first_word(&marker
, &image
, ":", EXTRACT_UNQUOTE
|EXTRACT_RETAIN_ESCAPE
);
1245 return log_debug_errno(r
, "Failed to parse marker: %s", marker
);
1249 a
= last_path_component(image
);
1251 if (image_name_is_valid(*image_name_or_path
)) {
1252 const char *e
, *underscore
;
1254 /* We shall match against an image name. In that case let's compare the last component, and optionally
1255 * allow either a suffix of ".raw" or a series of "/".
1256 * But allow matching on a different version of the same image, when a "_" is used as a separator. */
1257 underscore
= strchr(*image_name_or_path
, '_');
1259 if (strneq(a
, *image_name_or_path
, underscore
- *image_name_or_path
))
1264 e
= startswith(a
, *image_name_or_path
);
1268 if(!(e
[strspn(e
, "/")] == 0 || streq(e
, ".raw")))
1271 const char *b
, *underscore
;
1274 /* We shall match against a path. Let's ignore any prefix here though, as often there are many ways to
1275 * reach the same file. However, in this mode, let's validate any file suffix. */
1277 l
= strcspn(a
, "/");
1278 b
= last_path_component(*image_name_or_path
);
1280 if (strcspn(b
, "/") != l
)
1283 underscore
= strchr(b
, '_');
1287 if (!strneq(a
, b
, l
))
1295 static int test_chroot_dropin(
1299 const char *name_or_path
,
1300 char **extension_image_paths
,
1301 char **ret_marker
) {
1303 _cleanup_free_
char *line
= NULL
, *marker
= NULL
;
1304 _cleanup_fclose_
FILE *f
= NULL
;
1305 _cleanup_close_
int fd
= -1;
1306 const char *p
, *e
, *k
;
1313 /* We recognize unis created from portable images via the drop-in we created for them */
1315 p
= strjoina(fname
, ".d/20-portable.conf");
1316 fd
= openat(dirfd(d
), p
, O_RDONLY
|O_CLOEXEC
);
1318 if (errno
== ENOENT
)
1321 return log_debug_errno(errno
, "Failed to open %s/%s: %m", where
, p
);
1324 r
= take_fdopen_unlocked(&fd
, "r", &f
);
1326 return log_debug_errno(r
, "Failed to convert file handle: %m");
1328 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1330 return log_debug_errno(r
, "Failed to read from %s/%s: %m", where
, p
);
1332 e
= startswith(line
, PORTABLE_DROPIN_MARKER_BEGIN
);
1336 k
= endswith(e
, PORTABLE_DROPIN_MARKER_END
);
1340 marker
= strndup(e
, k
- e
);
1347 r
= marker_matches_images(marker
, name_or_path
, extension_image_paths
);
1350 *ret_marker
= TAKE_PTR(marker
);
1355 int portable_detach(
1357 const char *name_or_path
,
1358 char **extension_image_paths
,
1359 PortableFlags flags
,
1360 PortableChange
**changes
,
1362 sd_bus_error
*error
) {
1364 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1365 _cleanup_set_free_ Set
*unit_files
= NULL
, *markers
= NULL
;
1366 _cleanup_closedir_
DIR *d
= NULL
;
1367 const char *where
, *item
;
1372 assert(name_or_path
);
1374 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1378 where
= attached_path(&paths
, flags
);
1382 if (errno
== ENOENT
)
1385 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1388 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1389 _cleanup_free_
char *marker
= NULL
;
1390 UnitFileState state
;
1392 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1395 /* Filter out duplicates */
1396 if (set_contains(unit_files
, de
->d_name
))
1399 dirent_ensure_type(d
, de
);
1400 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1403 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, extension_image_paths
, &marker
);
1409 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1411 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1412 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_RUNTIME
, UNIT_FILE_LINKED_RUNTIME
))
1413 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
));
1415 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1418 if (!FLAGS_SET(flags
, PORTABLE_REATTACH
) && r
> 0)
1419 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active, can't detach.", de
->d_name
);
1421 r
= set_put_strdup(&unit_files
, de
->d_name
);
1423 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1425 for (const char *p
= marker
;;) {
1426 _cleanup_free_
char *image
= NULL
;
1428 r
= extract_first_word(&p
, &image
, ":", EXTRACT_UNESCAPE_SEPARATORS
|EXTRACT_RETAIN_ESCAPE
);
1430 return log_debug_errno(r
, "Failed to parse marker: %s", p
);
1434 if (path_is_absolute(image
) && !image_in_search_path(IMAGE_PORTABLE
, NULL
, image
)) {
1435 r
= set_ensure_consume(&markers
, &path_hash_ops_free
, TAKE_PTR(image
));
1442 if (set_isempty(unit_files
))
1445 SET_FOREACH(item
, unit_files
) {
1446 _cleanup_free_
char *md
= NULL
;
1449 if (unlinkat(dirfd(d
), item
, 0) < 0) {
1450 log_debug_errno(errno
, "Can't remove unit file %s/%s: %m", where
, item
);
1452 if (errno
!= ENOENT
&& ret
>= 0)
1455 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, item
, NULL
);
1457 FOREACH_STRING(suffix
, ".d/10-profile.conf", ".d/20-portable.conf") {
1458 _cleanup_free_
char *dropin
= NULL
;
1460 dropin
= strjoin(item
, suffix
);
1464 if (unlinkat(dirfd(d
), dropin
, 0) < 0) {
1465 log_debug_errno(errno
, "Can't remove drop-in %s/%s: %m", where
, dropin
);
1467 if (errno
!= ENOENT
&& ret
>= 0)
1470 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, dropin
, NULL
);
1473 md
= strjoin(item
, ".d");
1477 if (unlinkat(dirfd(d
), md
, AT_REMOVEDIR
) < 0) {
1478 log_debug_errno(errno
, "Can't remove drop-in directory %s/%s: %m", where
, md
);
1480 if (errno
!= ENOENT
&& ret
>= 0)
1483 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, md
, NULL
);
1486 /* Now, also drop any image symlink, for images outside of the sarch path */
1487 SET_FOREACH(item
, markers
) {
1488 _cleanup_free_
char *sl
= NULL
;
1491 r
= image_symlink(item
, flags
, &sl
);
1493 log_debug_errno(r
, "Failed to determine image symlink for '%s', ignoring: %m", item
);
1497 if (lstat(sl
, &st
) < 0) {
1498 log_debug_errno(errno
, "Failed to stat '%s', ignoring: %m", sl
);
1502 if (!S_ISLNK(st
.st_mode
)) {
1503 log_debug("Image '%s' is not a symlink, ignoring.", sl
);
1507 if (unlink(sl
) < 0) {
1508 log_debug_errno(errno
, "Can't remove image symlink '%s': %m", sl
);
1510 if (errno
!= ENOENT
&& ret
>= 0)
1513 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, sl
, NULL
);
1516 /* Try to remove the unit file directory, if we can */
1517 if (rmdir(where
) >= 0)
1518 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, where
, NULL
);
1523 log_debug("No unit files associated with '%s' found. Image not attached?", name_or_path
);
1524 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_UNIT
, "No unit files associated with '%s' found. Image not attached?", name_or_path
);
1527 static int portable_get_state_internal(
1529 const char *name_or_path
,
1530 PortableFlags flags
,
1532 sd_bus_error
*error
) {
1534 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1535 bool found_enabled
= false, found_running
= false;
1536 _cleanup_set_free_ Set
*unit_files
= NULL
;
1537 _cleanup_closedir_
DIR *d
= NULL
;
1542 assert(name_or_path
);
1545 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1549 where
= attached_path(&paths
, flags
);
1553 if (errno
== ENOENT
) {
1554 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1555 *ret
= PORTABLE_DETACHED
;
1559 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1562 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1563 UnitFileState state
;
1565 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1568 /* Filter out duplicates */
1569 if (set_contains(unit_files
, de
->d_name
))
1572 dirent_ensure_type(d
, de
);
1573 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1576 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, NULL
, NULL
);
1582 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1584 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1585 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_LINKED_RUNTIME
))
1586 found_enabled
= true;
1588 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1592 found_running
= true;
1594 r
= set_put_strdup(&unit_files
, de
->d_name
);
1596 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1599 *ret
= found_running
? (!set_isempty(unit_files
) && (flags
& PORTABLE_RUNTIME
) ? PORTABLE_RUNNING_RUNTIME
: PORTABLE_RUNNING
) :
1600 found_enabled
? (flags
& PORTABLE_RUNTIME
? PORTABLE_ENABLED_RUNTIME
: PORTABLE_ENABLED
) :
1601 !set_isempty(unit_files
) ? (flags
& PORTABLE_RUNTIME
? PORTABLE_ATTACHED_RUNTIME
: PORTABLE_ATTACHED
) : PORTABLE_DETACHED
;
1606 int portable_get_state(
1608 const char *name_or_path
,
1609 PortableFlags flags
,
1611 sd_bus_error
*error
) {
1613 PortableState state
;
1616 assert(name_or_path
);
1619 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1620 * the latter only if we didn't find anything in the former. */
1622 r
= portable_get_state_internal(bus
, name_or_path
, flags
& ~PORTABLE_RUNTIME
, &state
, error
);
1626 if (state
== PORTABLE_DETACHED
) {
1627 r
= portable_get_state_internal(bus
, name_or_path
, flags
| PORTABLE_RUNTIME
, &state
, error
);
1636 int portable_get_profiles(char ***ret
) {
1639 return conf_files_list_nulstr(ret
, NULL
, NULL
, CONF_FILES_DIRECTORY
|CONF_FILES_BASENAME
|CONF_FILES_FILTER_MASKED
, profile_dirs
);
1642 static const char* const portable_change_type_table
[_PORTABLE_CHANGE_TYPE_MAX
] = {
1643 [PORTABLE_COPY
] = "copy",
1644 [PORTABLE_MKDIR
] = "mkdir",
1645 [PORTABLE_SYMLINK
] = "symlink",
1646 [PORTABLE_UNLINK
] = "unlink",
1647 [PORTABLE_WRITE
] = "write",
1650 DEFINE_STRING_TABLE_LOOKUP(portable_change_type
, int);
1652 static const char* const portable_state_table
[_PORTABLE_STATE_MAX
] = {
1653 [PORTABLE_DETACHED
] = "detached",
1654 [PORTABLE_ATTACHED
] = "attached",
1655 [PORTABLE_ATTACHED_RUNTIME
] = "attached-runtime",
1656 [PORTABLE_ENABLED
] = "enabled",
1657 [PORTABLE_ENABLED_RUNTIME
] = "enabled-runtime",
1658 [PORTABLE_RUNNING
] = "running",
1659 [PORTABLE_RUNNING_RUNTIME
] = "running-runtime",
1662 DEFINE_STRING_TABLE_LOOKUP(portable_state
, PortableState
);