1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 #include "bus-common-errors.h"
5 #include "conf-files.h"
8 #include "dirent-util.h"
9 #include "dissect-image.h"
14 #include "locale-util.h"
15 #include "loop-util.h"
16 #include "machine-image.h"
18 #include "nulstr-util.h"
20 #include "path-lookup.h"
22 #include "process-util.h"
24 #include "signal-util.h"
25 #include "socket-util.h"
26 #include "sort-util.h"
27 #include "string-table.h"
29 #include "tmpfile-util.h"
30 #include "user-util.h"
32 static const char profile_dirs
[] = CONF_PATHS_NULSTR("systemd/portable/profile");
34 /* Markers used in the first line of our 20-portable.conf unit file drop-in to determine, that a) the unit file was
35 * dropped there by the portable service logic and b) for which image it was dropped there. */
36 #define PORTABLE_DROPIN_MARKER_BEGIN "# Drop-in created for image '"
37 #define PORTABLE_DROPIN_MARKER_END "', do not edit."
39 static bool prefix_match(const char *unit
, const char *prefix
) {
42 p
= startswith(unit
, prefix
);
46 /* Only respect prefixes followed by dash or dot or when there's a complete match */
47 return IN_SET(*p
, '-', '.', '@', 0);
50 static bool unit_match(const char *unit
, char **matches
) {
54 dot
= strrchr(unit
, '.');
58 if (!STR_IN_SET(dot
, ".service", ".socket", ".target", ".timer", ".path"))
61 /* Empty match expression means: everything */
62 if (strv_isempty(matches
))
65 /* Otherwise, at least one needs to match */
66 STRV_FOREACH(i
, matches
)
67 if (prefix_match(unit
, *i
))
73 static PortableMetadata
*portable_metadata_new(const char *name
, int fd
) {
76 m
= malloc0(offsetof(PortableMetadata
, name
) + strlen(name
) + 1);
80 strcpy(m
->name
, name
);
86 PortableMetadata
*portable_metadata_unref(PortableMetadata
*i
) {
96 static int compare_metadata(PortableMetadata
*const *x
, PortableMetadata
*const *y
) {
97 return strcmp((*x
)->name
, (*y
)->name
);
100 int portable_metadata_hashmap_to_sorted_array(Hashmap
*unit_files
, PortableMetadata
***ret
) {
102 _cleanup_free_ PortableMetadata
**sorted
= NULL
;
104 PortableMetadata
*item
;
107 sorted
= new(PortableMetadata
*, hashmap_size(unit_files
));
111 HASHMAP_FOREACH(item
, unit_files
, iterator
)
114 assert(k
== hashmap_size(unit_files
));
116 typesafe_qsort(sorted
, k
, compare_metadata
);
118 *ret
= TAKE_PTR(sorted
);
122 static int send_item(
128 struct cmsghdr cmsghdr
;
129 uint8_t buf
[CMSG_SPACE(sizeof(int))];
133 .msg_control
= &control
,
134 .msg_controllen
= sizeof(control
),
138 struct cmsghdr
*cmsg
;
139 _cleanup_close_
int data_fd
= -1;
141 assert(socket_fd
>= 0);
145 data_fd
= fd_duplicate_data_fd(fd
);
149 cmsg
= CMSG_FIRSTHDR(&mh
);
150 cmsg
->cmsg_level
= SOL_SOCKET
;
151 cmsg
->cmsg_type
= SCM_RIGHTS
;
152 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
153 memcpy(CMSG_DATA(cmsg
), &data_fd
, sizeof(int));
155 mh
.msg_controllen
= CMSG_SPACE(sizeof(int));
156 iovec
= IOVEC_MAKE_STRING(name
);
158 if (sendmsg(socket_fd
, &mh
, MSG_NOSIGNAL
) < 0)
164 static int recv_item(
170 struct cmsghdr cmsghdr
;
171 uint8_t buf
[CMSG_SPACE(sizeof(int))];
173 char buffer
[PATH_MAX
+2];
174 struct iovec iov
= IOVEC_INIT(buffer
, sizeof(buffer
)-1);
176 .msg_control
= &control
,
177 .msg_controllen
= sizeof(control
),
181 struct cmsghdr
*cmsg
;
182 _cleanup_close_
int found_fd
= -1;
186 assert(socket_fd
>= 0);
190 n
= recvmsg(socket_fd
, &mh
, MSG_CMSG_CLOEXEC
);
194 CMSG_FOREACH(cmsg
, &mh
) {
195 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
196 cmsg
->cmsg_type
== SCM_RIGHTS
) {
198 if (cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
199 assert(found_fd
< 0);
200 found_fd
= *(int*) CMSG_DATA(cmsg
);
211 copy
= strdup(buffer
);
216 *ret_fd
= TAKE_FD(found_fd
);
221 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(portable_metadata_hash_ops
, char, string_hash_func
, string_compare_func
,
222 PortableMetadata
, portable_metadata_unref
);
224 static int extract_now(
228 PortableMetadata
**ret_os_release
,
229 Hashmap
**ret_unit_files
) {
231 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
232 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
233 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
234 _cleanup_close_
int os_release_fd
= -1;
235 _cleanup_free_
char *os_release_path
= NULL
;
239 /* Extracts the metadata from a directory tree 'where'. Extracts two kinds of information: the /etc/os-release
240 * data, and all unit files matching the specified expression. Note that this function is called in two very
241 * different but also similar contexts. When the tool gets invoked on a directory tree, we'll process it
242 * directly, and in-process, and thus can return the requested data directly, via 'ret_os_release' and
243 * 'ret_unit_files'. However, if the tool is invoked on a raw disk image — which needs to be mounted first — we
244 * are invoked in a child process with private mounts and then need to send the collected data to our
245 * parent. To handle both cases in one call this function also gets a 'socket_fd' parameter, which when >= 0 is
246 * used to send the data to the parent. */
250 /* First, find /etc/os-release and send it upstream (or just save it). */
251 r
= open_os_release(where
, &os_release_path
, &os_release_fd
);
253 log_debug_errno(r
, "Couldn't acquire os-release file, ignoring: %m");
255 if (socket_fd
>= 0) {
256 r
= send_item(socket_fd
, "/etc/os-release", os_release_fd
);
258 return log_debug_errno(r
, "Failed to send os-release file: %m");
261 if (ret_os_release
) {
262 os_release
= portable_metadata_new("/etc/os-release", os_release_fd
);
267 os_release
->source
= TAKE_PTR(os_release_path
);
271 /* Then, send unit file data to the parent (or/and add it to the hashmap). For that we use our usual unit
272 * discovery logic. Note that we force looking inside of /lib/systemd/system/ for units too, as we mightbe
273 * compiled for a split-usr system but the image might be a legacy-usr one. */
274 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, where
);
276 return log_debug_errno(r
, "Failed to acquire lookup paths: %m");
278 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
282 STRV_FOREACH(i
, paths
.search_path
) {
283 _cleanup_free_
char *resolved
= NULL
;
284 _cleanup_closedir_
DIR *d
= NULL
;
287 r
= chase_symlinks_and_opendir(*i
, where
, 0, &resolved
, &d
);
289 log_debug_errno(r
, "Failed to open unit path '%s', ignoring: %m", *i
);
293 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to read directory: %m")) {
294 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*m
= NULL
;
295 _cleanup_close_
int fd
= -1;
297 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
300 if (!unit_match(de
->d_name
, matches
))
303 /* Filter out duplicates */
304 if (hashmap_get(unit_files
, de
->d_name
))
307 dirent_ensure_type(d
, de
);
308 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
311 fd
= openat(dirfd(d
), de
->d_name
, O_CLOEXEC
|O_RDONLY
);
313 log_debug_errno(errno
, "Failed to open unit file '%s', ignoring: %m", de
->d_name
);
317 if (socket_fd
>= 0) {
318 r
= send_item(socket_fd
, de
->d_name
, fd
);
320 return log_debug_errno(r
, "Failed to send unit metadata to parent: %m");
323 m
= portable_metadata_new(de
->d_name
, fd
);
328 m
->source
= strjoin(resolved
, "/", de
->d_name
);
332 r
= hashmap_put(unit_files
, m
->name
, m
);
334 return log_debug_errno(r
, "Failed to add unit to hashmap: %m");
340 *ret_os_release
= TAKE_PTR(os_release
);
342 *ret_unit_files
= TAKE_PTR(unit_files
);
347 static int portable_extract_by_path(
350 PortableMetadata
**ret_os_release
,
351 Hashmap
**ret_unit_files
,
352 sd_bus_error
*error
) {
354 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
355 _cleanup_(portable_metadata_unrefp
) PortableMetadata
* os_release
= NULL
;
356 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
361 r
= loop_device_make_by_path(path
, O_RDONLY
, &d
);
363 /* We can't turn this into a loop-back block device, and this returns EISDIR? Then this is a directory
364 * tree and not a raw device. It's easy then. */
366 r
= extract_now(path
, matches
, -1, &os_release
, &unit_files
);
371 return log_debug_errno(r
, "Failed to set up loopback device: %m");
373 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
374 _cleanup_(rmdir_and_freep
) char *tmpdir
= NULL
;
375 _cleanup_(close_pairp
) int seq
[2] = { -1, -1 };
376 _cleanup_(sigkill_waitp
) pid_t child
= 0;
378 /* We now have a loopback block device, let's fork off a child in its own mount namespace, mount it
379 * there, and extract the metadata we need. The metadata is sent from the child back to us. */
381 BLOCK_SIGNALS(SIGCHLD
);
383 r
= mkdtemp_malloc("/tmp/inspect-XXXXXX", &tmpdir
);
385 return log_debug_errno(r
, "Failed to create temporary directory: %m");
387 r
= dissect_image(d
->fd
, NULL
, 0, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_REQUIRE_ROOT
|DISSECT_IMAGE_DISCARD_ON_LOOP
, &m
);
389 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't identify a suitable partition table or file system in '%s'.", path
);
390 else if (r
== -EADDRNOTAVAIL
)
391 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No root partition for specified root hash found in '%s'.", path
);
392 else if (r
== -ENOTUNIQ
)
393 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Multiple suitable root partitions found in image '%s'.", path
);
394 else if (r
== -ENXIO
)
395 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No suitable root partition found in image '%s'.", path
);
396 else if (r
== -EPROTONOSUPPORT
)
397 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
);
401 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, seq
) < 0)
402 return log_debug_errno(errno
, "Failed to allocated SOCK_SEQPACKET socket: %m");
404 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
|FORK_LOG
, &child
);
408 seq
[0] = safe_close(seq
[0]);
410 r
= dissected_image_mount(m
, tmpdir
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
412 log_debug_errno(r
, "Failed to mount dissected image: %m");
416 r
= extract_now(tmpdir
, matches
, seq
[1], NULL
, NULL
);
419 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
422 seq
[1] = safe_close(seq
[1]);
424 unit_files
= hashmap_new(&portable_metadata_hash_ops
);
429 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*add
= NULL
;
430 _cleanup_free_
char *name
= NULL
;
431 _cleanup_close_
int fd
= -1;
433 r
= recv_item(seq
[0], &name
, &fd
);
435 return log_debug_errno(r
, "Failed to receive item: %m");
437 /* We can't really distuingish a zero-length datagram without any fds from EOF (both are signalled the
438 * same way by recvmsg()). Hence, accept either as end notification. */
439 if (isempty(name
) && fd
< 0)
442 if (isempty(name
) || fd
< 0) {
443 log_debug("Invalid item sent from child.");
447 add
= portable_metadata_new(name
, fd
);
452 /* Note that we do not initialize 'add->source' here, as the source path is not usable here as
453 * it refers to a path only valid in the short-living namespaced child process we forked
456 if (PORTABLE_METADATA_IS_UNIT(add
)) {
457 r
= hashmap_put(unit_files
, add
->name
, add
);
459 return log_debug_errno(r
, "Failed to add item to unit file list: %m");
463 } else if (PORTABLE_METADATA_IS_OS_RELEASE(add
)) {
466 os_release
= TAKE_PTR(add
);
468 assert_not_reached("Unexpected metadata item from child.");
471 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
478 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Image '%s' lacks os-release data, refusing.", path
);
480 if (hashmap_isempty(unit_files
))
481 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't find any matching unit files in image '%s', refusing.", path
);
484 *ret_unit_files
= TAKE_PTR(unit_files
);
487 *ret_os_release
= TAKE_PTR(os_release
);
492 int portable_extract(
493 const char *name_or_path
,
495 PortableMetadata
**ret_os_release
,
496 Hashmap
**ret_unit_files
,
497 sd_bus_error
*error
) {
499 _cleanup_(image_unrefp
) Image
*image
= NULL
;
502 assert(name_or_path
);
504 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, &image
);
508 return portable_extract_by_path(image
->path
, matches
, ret_os_release
, ret_unit_files
, error
);
511 static int unit_file_is_active(
514 sd_bus_error
*error
) {
516 static const char *const active_states
[] = {
528 /* If we are looking at a plain or instance things are easy, we can just query the state */
529 if (unit_name_is_valid(name
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
)) {
530 _cleanup_free_
char *path
= NULL
, *buf
= NULL
;
532 path
= unit_dbus_path_from_name(name
);
536 r
= sd_bus_get_property_string(
538 "org.freedesktop.systemd1",
540 "org.freedesktop.systemd1.Unit",
545 return log_debug_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(error
, r
));
547 return strv_contains((char**) active_states
, buf
);
550 /* Otherwise we need to enumerate. But let's build the most restricted query we can */
551 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
552 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
553 const char *at
, *prefix
, *joined
;
555 r
= sd_bus_message_new_method_call(
558 "org.freedesktop.systemd1",
559 "/org/freedesktop/systemd1",
560 "org.freedesktop.systemd1.Manager",
561 "ListUnitsByPatterns");
565 r
= sd_bus_message_append_strv(m
, (char**) active_states
);
569 at
= strchr(name
, '@');
572 prefix
= strndupa(name
, at
+ 1 - name
);
573 joined
= strjoina(prefix
, "*", at
+ 1);
575 r
= sd_bus_message_append_strv(m
, STRV_MAKE(joined
));
579 r
= sd_bus_call(bus
, m
, 0, error
, &reply
);
581 return log_debug_errno(r
, "Failed to list units: %s", bus_error_message(error
, r
));
583 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
587 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_STRUCT
, "ssssssouso");
597 static int portable_changes_add(
598 PortableChange
**changes
,
600 PortableChangeType type
,
602 const char *source
) {
604 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
608 assert(!changes
== !n_changes
);
613 c
= reallocarray(*changes
, *n_changes
+ 1, sizeof(PortableChange
));
622 path_simplify(p
, false);
629 path_simplify(s
, false);
632 c
[(*n_changes
)++] = (PortableChange
) {
635 .source
= TAKE_PTR(s
),
641 static int portable_changes_add_with_prefix(
642 PortableChange
**changes
,
644 PortableChangeType type
,
647 const char *source
) {
650 assert(!changes
== !n_changes
);
656 path
= strjoina(prefix
, "/", path
);
659 source
= strjoina(prefix
, "/", source
);
662 return portable_changes_add(changes
, n_changes
, type
, path
, source
);
665 void portable_changes_free(PortableChange
*changes
, size_t n_changes
) {
668 assert(changes
|| n_changes
== 0);
670 for (i
= 0; i
< n_changes
; i
++) {
671 free(changes
[i
].path
);
672 free(changes
[i
].source
);
678 static int install_chroot_dropin(
679 const char *image_path
,
681 const PortableMetadata
*m
,
682 const char *dropin_dir
,
684 PortableChange
**changes
,
687 _cleanup_free_
char *text
= NULL
, *dropin
= NULL
;
694 dropin
= strjoin(dropin_dir
, "/20-portable.conf");
698 text
= strjoin(PORTABLE_DROPIN_MARKER_BEGIN
, image_path
, PORTABLE_DROPIN_MARKER_END
"\n");
702 if (endswith(m
->name
, ".service"))
703 if (!strextend(&text
,
706 IN_SET(type
, IMAGE_DIRECTORY
, IMAGE_SUBVOLUME
) ? "RootDirectory=" : "RootImage=", image_path
, "\n"
707 "Environment=PORTABLE=", basename(image_path
), "\n"
708 "LogExtraFields=PORTABLE=", basename(image_path
), "\n",
713 r
= write_string_file(dropin
, text
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
715 return log_debug_errno(r
, "Failed to write '%s': %m", dropin
);
717 (void) portable_changes_add(changes
, n_changes
, PORTABLE_WRITE
, dropin
, NULL
);
720 *ret_dropin
= TAKE_PTR(dropin
);
725 static int find_profile(const char *name
, const char *unit
, char **ret
) {
731 assert_se(dot
= strrchr(unit
, '.'));
733 NULSTR_FOREACH(p
, profile_dirs
) {
734 _cleanup_free_
char *joined
;
736 joined
= strjoin(p
, "/", name
, "/", dot
+ 1, ".conf");
740 if (laccess(joined
, F_OK
) >= 0) {
741 *ret
= TAKE_PTR(joined
);
752 static int install_profile_dropin(
753 const char *image_path
,
754 const PortableMetadata
*m
,
755 const char *dropin_dir
,
759 PortableChange
**changes
,
762 _cleanup_free_
char *dropin
= NULL
, *from
= NULL
;
772 r
= find_profile(profile
, m
->name
, &from
);
775 return log_debug_errno(errno
, "Profile '%s' is not accessible: %m", profile
);
777 log_debug_errno(errno
, "Skipping link to profile '%s', as it does not exist: %m", profile
);
781 dropin
= strjoin(dropin_dir
, "/10-profile.conf");
785 if (flags
& PORTABLE_PREFER_COPY
) {
787 r
= copy_file_atomic(from
, dropin
, 0644, 0, 0, COPY_REFLINK
);
789 return log_debug_errno(r
, "Failed to copy %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW
), dropin
);
791 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, dropin
, from
);
795 if (symlink(from
, dropin
) < 0)
796 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", from
, special_glyph(SPECIAL_GLYPH_ARROW
), dropin
);
798 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, dropin
, from
);
802 *ret_dropin
= TAKE_PTR(dropin
);
807 static const char *attached_path(const LookupPaths
*paths
, PortableFlags flags
) {
812 if (flags
& PORTABLE_RUNTIME
)
813 where
= paths
->runtime_attached
;
815 where
= paths
->persistent_attached
;
821 static int attach_unit_file(
822 const LookupPaths
*paths
,
823 const char *image_path
,
825 const PortableMetadata
*m
,
828 PortableChange
**changes
,
831 _cleanup_(unlink_and_freep
) char *chroot_dropin
= NULL
, *profile_dropin
= NULL
;
832 _cleanup_(rmdir_and_freep
) char *dropin_dir
= NULL
;
833 const char *where
, *path
;
839 assert(PORTABLE_METADATA_IS_UNIT(m
));
841 where
= attached_path(paths
, flags
);
843 (void) mkdir_parents(where
, 0755);
844 if (mkdir(where
, 0755) < 0) {
848 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, where
, NULL
);
850 path
= strjoina(where
, "/", m
->name
);
851 dropin_dir
= strjoin(path
, ".d");
855 if (mkdir(dropin_dir
, 0755) < 0) {
859 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, dropin_dir
, NULL
);
861 /* We install the drop-ins first, and the actual unit file last to achieve somewhat atomic behaviour if PID 1
862 * is reloaded while we are creating things here: as long as only the drop-ins exist the unit doesn't exist at
865 r
= install_chroot_dropin(image_path
, type
, m
, dropin_dir
, &chroot_dropin
, changes
, n_changes
);
869 r
= install_profile_dropin(image_path
, m
, dropin_dir
, profile
, flags
, &profile_dropin
, changes
, n_changes
);
873 if ((flags
& PORTABLE_PREFER_SYMLINK
) && m
->source
) {
875 if (symlink(m
->source
, path
) < 0)
876 return log_debug_errno(errno
, "Failed to symlink unit file '%s': %m", path
);
878 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, path
, m
->source
);
881 _cleanup_(unlink_and_freep
) char *tmp
= NULL
;
882 _cleanup_close_
int fd
= -1;
884 fd
= open_tmpfile_linkable(where
, O_WRONLY
|O_CLOEXEC
, &tmp
);
886 return log_debug_errno(fd
, "Failed to create unit file '%s': %m", path
);
888 r
= copy_bytes(m
->fd
, fd
, UINT64_MAX
, COPY_REFLINK
);
890 return log_debug_errno(r
, "Failed to copy unit file '%s': %m", path
);
892 if (fchmod(fd
, 0644) < 0)
893 return log_debug_errno(errno
, "Failed to change unit file access mode for '%s': %m", path
);
895 r
= link_tmpfile(fd
, tmp
, path
);
897 return log_debug_errno(r
, "Failed to install unit file '%s': %m", path
);
901 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, path
, m
->source
);
904 /* All is established now, now let's disable any rollbacks */
905 chroot_dropin
= mfree(chroot_dropin
);
906 profile_dropin
= mfree(profile_dropin
);
907 dropin_dir
= mfree(dropin_dir
);
912 static int image_symlink(
913 const char *image_path
,
917 const char *fn
, *where
;
923 fn
= last_path_component(image_path
);
925 if (flags
& PORTABLE_RUNTIME
)
926 where
= "/run/portables/";
928 where
= "/etc/portables/";
930 joined
= strjoin(where
, fn
);
938 static int install_image_symlink(
939 const char *image_path
,
941 PortableChange
**changes
,
944 _cleanup_free_
char *sl
= NULL
;
949 /* If the image is outside of the image search also link it into it, so that it can be found with short image
950 * names and is listed among the images. */
952 if (image_in_search_path(IMAGE_PORTABLE
, image_path
))
955 r
= image_symlink(image_path
, flags
, &sl
);
957 return log_debug_errno(r
, "Failed to generate image symlink path: %m");
959 (void) mkdir_parents(sl
, 0755);
961 if (symlink(image_path
, sl
) < 0)
962 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", image_path
, special_glyph(SPECIAL_GLYPH_ARROW
), sl
);
964 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, sl
, image_path
);
970 const char *name_or_path
,
974 PortableChange
**changes
,
976 sd_bus_error
*error
) {
978 _cleanup_hashmap_free_ Hashmap
*unit_files
= NULL
;
979 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
980 _cleanup_(image_unrefp
) Image
*image
= NULL
;
981 PortableMetadata
*item
;
985 assert(name_or_path
);
987 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, &image
);
991 r
= portable_extract_by_path(image
->path
, matches
, NULL
, &unit_files
, error
);
995 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
999 HASHMAP_FOREACH(item
, unit_files
, iterator
) {
1000 r
= unit_file_exists(UNIT_FILE_SYSTEM
, &paths
, item
->name
);
1002 return sd_bus_error_set_errnof(error
, r
, "Failed to determine whether unit '%s' exists on the host: %m", item
->name
);
1004 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' exists on the host already, refusing.", item
->name
);
1006 r
= unit_file_is_active(bus
, item
->name
, error
);
1010 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active already, refusing.", item
->name
);
1013 HASHMAP_FOREACH(item
, unit_files
, iterator
) {
1014 r
= attach_unit_file(&paths
, image
->path
, image
->type
, item
, profile
, flags
, changes
, n_changes
);
1019 /* We don't care too much for the image symlink, it's just a convenience thing, it's not necessary for proper
1020 * operation otherwise. */
1021 (void) install_image_symlink(image
->path
, flags
, changes
, n_changes
);
1026 static bool marker_matches_image(const char *marker
, const char *name_or_path
) {
1030 assert(name_or_path
);
1032 a
= last_path_component(marker
);
1034 if (image_name_is_valid(name_or_path
)) {
1037 /* We shall match against an image name. In that case let's compare the last component, and optionally
1038 * allow either a suffix of ".raw" or a series of "/". */
1040 e
= startswith(a
, name_or_path
);
1045 e
[strspn(e
, "/")] == 0 ||
1051 /* We shall match against a path. Let's ignore any prefix here though, as often there are many ways to
1052 * reach the same file. However, in this mode, let's validate any file suffix. */
1054 l
= strcspn(a
, "/");
1055 b
= last_path_component(name_or_path
);
1057 if (strcspn(b
, "/") != l
)
1060 return memcmp(a
, b
, l
) == 0;
1064 static int test_chroot_dropin(
1068 const char *name_or_path
,
1069 char **ret_marker
) {
1071 _cleanup_free_
char *line
= NULL
, *marker
= NULL
;
1072 _cleanup_fclose_
FILE *f
= NULL
;
1073 _cleanup_close_
int fd
= -1;
1074 const char *p
, *e
, *k
;
1081 /* We recognize unis created from portable images via the drop-in we created for them */
1083 p
= strjoina(fname
, ".d/20-portable.conf");
1084 fd
= openat(dirfd(d
), p
, O_RDONLY
|O_CLOEXEC
);
1086 if (errno
== ENOENT
)
1089 return log_debug_errno(errno
, "Failed to open %s/%s: %m", where
, p
);
1092 r
= fdopen_unlocked(fd
, "r", &f
);
1094 return log_debug_errno(r
, "Failed to convert file handle: %m");
1097 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1099 return log_debug_errno(r
, "Failed to read from %s/%s: %m", where
, p
);
1101 e
= startswith(line
, PORTABLE_DROPIN_MARKER_BEGIN
);
1105 k
= endswith(e
, PORTABLE_DROPIN_MARKER_END
);
1109 marker
= strndup(e
, k
- e
);
1116 r
= marker_matches_image(marker
, name_or_path
);
1119 *ret_marker
= TAKE_PTR(marker
);
1124 int portable_detach(
1126 const char *name_or_path
,
1127 PortableFlags flags
,
1128 PortableChange
**changes
,
1130 sd_bus_error
*error
) {
1132 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1133 _cleanup_set_free_free_ Set
*unit_files
= NULL
, *markers
= NULL
;
1134 _cleanup_closedir_
DIR *d
= NULL
;
1135 const char *where
, *item
;
1141 assert(name_or_path
);
1143 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1147 where
= attached_path(&paths
, flags
);
1151 if (errno
== ENOENT
)
1154 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1157 unit_files
= set_new(&string_hash_ops
);
1161 markers
= set_new(&path_hash_ops
);
1165 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1166 _cleanup_free_
char *marker
= NULL
;
1167 UnitFileState state
;
1169 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1172 /* Filter out duplicates */
1173 if (set_get(unit_files
, de
->d_name
))
1176 dirent_ensure_type(d
, de
);
1177 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1180 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, &marker
);
1186 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1188 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1189 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_RUNTIME
))
1190 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
));
1192 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1196 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active, can't detach.", de
->d_name
);
1198 r
= set_put_strdup(unit_files
, de
->d_name
);
1200 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1202 if (path_is_absolute(marker
) &&
1203 !image_in_search_path(IMAGE_PORTABLE
, marker
)) {
1205 r
= set_ensure_allocated(&markers
, &path_hash_ops
);
1209 r
= set_put(markers
, marker
);
1212 else if (r
!= -EEXIST
)
1217 if (set_isempty(unit_files
))
1220 SET_FOREACH(item
, unit_files
, iterator
) {
1221 _cleanup_free_
char *md
= NULL
;
1224 if (unlinkat(dirfd(d
), item
, 0) < 0) {
1225 log_debug_errno(errno
, "Can't remove unit file %s/%s: %m", where
, item
);
1227 if (errno
!= ENOENT
&& ret
>= 0)
1230 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, item
, NULL
);
1232 FOREACH_STRING(suffix
, ".d/10-profile.conf", ".d/20-portable.conf") {
1233 _cleanup_free_
char *dropin
= NULL
;
1235 dropin
= strjoin(item
, suffix
);
1239 if (unlinkat(dirfd(d
), dropin
, 0) < 0) {
1240 log_debug_errno(errno
, "Can't remove drop-in %s/%s: %m", where
, dropin
);
1242 if (errno
!= ENOENT
&& ret
>= 0)
1245 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, dropin
, NULL
);
1248 md
= strjoin(item
, ".d");
1252 if (unlinkat(dirfd(d
), md
, AT_REMOVEDIR
) < 0) {
1253 log_debug_errno(errno
, "Can't remove drop-in directory %s/%s: %m", where
, md
);
1255 if (errno
!= ENOENT
&& ret
>= 0)
1258 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, md
, NULL
);
1261 /* Now, also drop any image symlink, for images outside of the sarch path */
1262 SET_FOREACH(item
, markers
, iterator
) {
1263 _cleanup_free_
char *sl
= NULL
;
1266 r
= image_symlink(item
, flags
, &sl
);
1268 log_debug_errno(r
, "Failed to determine image symlink for '%s', ignoring: %m", item
);
1272 if (lstat(sl
, &st
) < 0) {
1273 log_debug_errno(errno
, "Failed to stat '%s', ignoring: %m", sl
);
1277 if (!S_ISLNK(st
.st_mode
)) {
1278 log_debug("Image '%s' is not a symlink, ignoring.", sl
);
1282 if (unlink(sl
) < 0) {
1283 log_debug_errno(errno
, "Can't remove image symlink '%s': %m", sl
);
1285 if (errno
!= ENOENT
&& ret
>= 0)
1288 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, sl
, NULL
);
1291 /* Try to remove the unit file directory, if we can */
1292 if (rmdir(where
) >= 0)
1293 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, where
, NULL
);
1298 log_debug("No unit files associated with '%s' found. Image not attached?", name_or_path
);
1299 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_UNIT
, "No unit files associated with '%s' found. Image not attached?", name_or_path
);
1302 static int portable_get_state_internal(
1304 const char *name_or_path
,
1305 PortableFlags flags
,
1307 sd_bus_error
*error
) {
1309 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1310 bool found_enabled
= false, found_running
= false;
1311 _cleanup_set_free_free_ Set
*unit_files
= NULL
;
1312 _cleanup_closedir_
DIR *d
= NULL
;
1317 assert(name_or_path
);
1320 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1324 where
= attached_path(&paths
, flags
);
1328 if (errno
== ENOENT
) {
1329 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1330 *ret
= PORTABLE_DETACHED
;
1334 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1337 unit_files
= set_new(&string_hash_ops
);
1341 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1342 UnitFileState state
;
1344 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1347 /* Filter out duplicates */
1348 if (set_get(unit_files
, de
->d_name
))
1351 dirent_ensure_type(d
, de
);
1352 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1355 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, NULL
);
1361 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1363 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1364 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_LINKED_RUNTIME
))
1365 found_enabled
= true;
1367 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1371 found_running
= true;
1373 r
= set_put_strdup(unit_files
, de
->d_name
);
1375 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1378 *ret
= found_running
? (!set_isempty(unit_files
) && (flags
& PORTABLE_RUNTIME
) ? PORTABLE_RUNNING_RUNTIME
: PORTABLE_RUNNING
) :
1379 found_enabled
? (flags
& PORTABLE_RUNTIME
? PORTABLE_ENABLED_RUNTIME
: PORTABLE_ENABLED
) :
1380 !set_isempty(unit_files
) ? (flags
& PORTABLE_RUNTIME
? PORTABLE_ATTACHED_RUNTIME
: PORTABLE_ATTACHED
) : PORTABLE_DETACHED
;
1385 int portable_get_state(
1387 const char *name_or_path
,
1388 PortableFlags flags
,
1390 sd_bus_error
*error
) {
1392 PortableState state
;
1395 assert(name_or_path
);
1398 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1399 * the latter only if we didn't find anything in the former. */
1401 r
= portable_get_state_internal(bus
, name_or_path
, flags
& ~PORTABLE_RUNTIME
, &state
, error
);
1405 if (state
== PORTABLE_DETACHED
) {
1406 r
= portable_get_state_internal(bus
, name_or_path
, flags
| PORTABLE_RUNTIME
, &state
, error
);
1415 int portable_get_profiles(char ***ret
) {
1418 return conf_files_list_nulstr(ret
, NULL
, NULL
, CONF_FILES_DIRECTORY
|CONF_FILES_BASENAME
|CONF_FILES_FILTER_MASKED
, profile_dirs
);
1421 static const char* const portable_change_type_table
[_PORTABLE_CHANGE_TYPE_MAX
] = {
1422 [PORTABLE_COPY
] = "copy",
1423 [PORTABLE_MKDIR
] = "mkdir",
1424 [PORTABLE_SYMLINK
] = "symlink",
1425 [PORTABLE_UNLINK
] = "unlink",
1426 [PORTABLE_WRITE
] = "write",
1429 DEFINE_STRING_TABLE_LOOKUP(portable_change_type
, PortableChangeType
);
1431 static const char* const portable_state_table
[_PORTABLE_STATE_MAX
] = {
1432 [PORTABLE_DETACHED
] = "detached",
1433 [PORTABLE_ATTACHED
] = "attached",
1434 [PORTABLE_ATTACHED_RUNTIME
] = "attached-runtime",
1435 [PORTABLE_ENABLED
] = "enabled",
1436 [PORTABLE_ENABLED_RUNTIME
] = "enabled-runtime",
1437 [PORTABLE_RUNNING
] = "running",
1438 [PORTABLE_RUNNING_RUNTIME
] = "running-runtime",
1441 DEFINE_STRING_TABLE_LOOKUP(portable_state
, PortableState
);