1 /* SPDX-License-Identifier: LGPL-2.1+ */
5 #include "bus-common-errors.h"
7 #include "conf-files.h"
10 #include "dirent-util.h"
11 #include "dissect-image.h"
16 #include "locale-util.h"
17 #include "loop-util.h"
18 #include "machine-image.h"
21 #include "path-lookup.h"
23 #include "process-util.h"
25 #include "signal-util.h"
26 #include "socket-util.h"
27 #include "string-table.h"
29 #include "user-util.h"
31 static const char profile_dirs
[] = CONF_PATHS_NULSTR("systemd/portable/profile");
33 /* Markers used in the first line of our 20-portable.conf unit file drop-in to determine, that a) the unit file was
34 * dropped there by the portable service logic and b) for which image it was dropped there. */
35 #define PORTABLE_DROPIN_MARKER_BEGIN "# Drop-in created for image '"
36 #define PORTABLE_DROPIN_MARKER_END "', do not edit."
38 static bool prefix_match(const char *unit
, const char *prefix
) {
41 p
= startswith(unit
, prefix
);
45 /* Only respect prefixes followed by dash or dot or when there's a complete match */
46 return IN_SET(*p
, '-', '.', '@', 0);
49 static bool unit_match(const char *unit
, char **matches
) {
53 dot
= strrchr(unit
, '.');
57 if (!STR_IN_SET(dot
, ".service", ".socket", ".target", ".timer", ".path"))
60 /* Empty match expression means: everything */
61 if (strv_isempty(matches
))
64 /* Otherwise, at least one needs to match */
65 STRV_FOREACH(i
, matches
)
66 if (prefix_match(unit
, *i
))
72 static PortableMetadata
*portable_metadata_new(const char *name
, int fd
) {
75 m
= malloc0(offsetof(PortableMetadata
, name
) + strlen(name
) + 1);
79 strcpy(m
->name
, name
);
85 PortableMetadata
*portable_metadata_unref(PortableMetadata
*i
) {
95 Hashmap
*portable_metadata_hashmap_unref(Hashmap
*h
) {
100 i
= hashmap_steal_first(h
);
104 portable_metadata_unref(i
);
107 return hashmap_free(h
);
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
;
118 PortableMetadata
*item
;
121 sorted
= new(PortableMetadata
*, hashmap_size(unit_files
));
125 HASHMAP_FOREACH(item
, unit_files
, iterator
)
128 assert(k
== hashmap_size(unit_files
));
130 typesafe_qsort(sorted
, k
, compare_metadata
);
132 *ret
= TAKE_PTR(sorted
);
136 static int send_item(
142 struct cmsghdr cmsghdr
;
143 uint8_t buf
[CMSG_SPACE(sizeof(int))];
147 .msg_control
= &control
,
148 .msg_controllen
= sizeof(control
),
152 struct cmsghdr
*cmsg
;
153 _cleanup_close_
int data_fd
= -1;
155 assert(socket_fd
>= 0);
159 data_fd
= fd_duplicate_data_fd(fd
);
163 cmsg
= CMSG_FIRSTHDR(&mh
);
164 cmsg
->cmsg_level
= SOL_SOCKET
;
165 cmsg
->cmsg_type
= SCM_RIGHTS
;
166 cmsg
->cmsg_len
= CMSG_LEN(sizeof(int));
167 memcpy(CMSG_DATA(cmsg
), &data_fd
, sizeof(int));
169 mh
.msg_controllen
= CMSG_SPACE(sizeof(int));
170 iovec
= IOVEC_MAKE_STRING(name
);
172 if (sendmsg(socket_fd
, &mh
, MSG_NOSIGNAL
) < 0)
178 static int recv_item(
184 struct cmsghdr cmsghdr
;
185 uint8_t buf
[CMSG_SPACE(sizeof(int))];
187 char buffer
[PATH_MAX
+2];
188 struct iovec iov
= IOVEC_INIT(buffer
, sizeof(buffer
)-1);
190 .msg_control
= &control
,
191 .msg_controllen
= sizeof(control
),
195 struct cmsghdr
*cmsg
;
196 _cleanup_close_
int found_fd
= -1;
200 assert(socket_fd
>= 0);
204 n
= recvmsg(socket_fd
, &mh
, MSG_CMSG_CLOEXEC
);
208 CMSG_FOREACH(cmsg
, &mh
) {
209 if (cmsg
->cmsg_level
== SOL_SOCKET
&&
210 cmsg
->cmsg_type
== SCM_RIGHTS
) {
212 if (cmsg
->cmsg_len
== CMSG_LEN(sizeof(int))) {
213 assert(found_fd
< 0);
214 found_fd
= *(int*) CMSG_DATA(cmsg
);
225 copy
= strdup(buffer
);
230 *ret_fd
= TAKE_FD(found_fd
);
235 static int extract_now(
239 PortableMetadata
**ret_os_release
,
240 Hashmap
**ret_unit_files
) {
242 _cleanup_(portable_metadata_hashmap_unrefp
) Hashmap
*unit_files
= NULL
;
243 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*os_release
= NULL
;
244 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
245 _cleanup_close_
int os_release_fd
= -1;
246 _cleanup_free_
char *os_release_path
= NULL
;
250 /* Extracts the metadata from a directory tree 'where'. Extracts two kinds of information: the /etc/os-release
251 * data, and all unit files matching the specified expression. Note that this function is called in two very
252 * different but also similar contexts. When the tool gets invoked on a directory tree, we'll process it
253 * directly, and in-process, and thus can return the requested data directly, via 'ret_os_release' and
254 * 'ret_unit_files'. However, if the tool is invoked on a raw disk image — which needs to be mounted first — we
255 * are invoked in a child process with private mounts and then need to send the collected data to our
256 * parent. To handle both cases in one call this function also gets a 'socket_fd' parameter, which when >= 0 is
257 * used to send the data to the parent. */
261 /* First, find /etc/os-release and send it upstream (or just save it). */
262 r
= open_os_release(where
, &os_release_path
, &os_release_fd
);
264 log_debug_errno(r
, "Couldn't acquire os-release file, ignoring: %m");
266 if (socket_fd
>= 0) {
267 r
= send_item(socket_fd
, "/etc/os-release", os_release_fd
);
269 return log_debug_errno(r
, "Failed to send os-release file: %m");
272 if (ret_os_release
) {
273 os_release
= portable_metadata_new("/etc/os-release", os_release_fd
);
278 os_release
->source
= TAKE_PTR(os_release_path
);
282 /* Then, send unit file data to the parent (or/and add it to the hashmap). For that we use our usual unit
283 * discovery logic. Note that we force looking inside of /lib/systemd/system/ for units too, as we mightbe
284 * compiled for a split-usr system but the image might be a legacy-usr one. */
285 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, where
);
287 return log_debug_errno(r
, "Failed to acquire lookup paths: %m");
289 unit_files
= hashmap_new(&string_hash_ops
);
293 STRV_FOREACH(i
, paths
.search_path
) {
294 _cleanup_free_
char *resolved
= NULL
;
295 _cleanup_closedir_
DIR *d
= NULL
;
298 r
= chase_symlinks_and_opendir(*i
, where
, 0, &resolved
, &d
);
300 log_debug_errno(r
, "Failed to open unit path '%s', ignoring: %m", *i
);
304 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to read directory: %m")) {
305 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*m
= NULL
;
306 _cleanup_close_
int fd
= -1;
308 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
311 if (!unit_match(de
->d_name
, matches
))
314 /* Filter out duplicates */
315 if (hashmap_get(unit_files
, de
->d_name
))
318 dirent_ensure_type(d
, de
);
319 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
322 fd
= openat(dirfd(d
), de
->d_name
, O_CLOEXEC
|O_RDONLY
);
324 log_debug_errno(errno
, "Failed to open unit file '%s', ignoring: %m", de
->d_name
);
328 if (socket_fd
>= 0) {
329 r
= send_item(socket_fd
, de
->d_name
, fd
);
331 return log_debug_errno(r
, "Failed to send unit metadata to parent: %m");
334 m
= portable_metadata_new(de
->d_name
, fd
);
339 m
->source
= strjoin(resolved
, "/", de
->d_name
);
343 r
= hashmap_put(unit_files
, m
->name
, m
);
345 return log_debug_errno(r
, "Failed to add unit to hashmap: %m");
351 *ret_os_release
= TAKE_PTR(os_release
);
353 *ret_unit_files
= TAKE_PTR(unit_files
);
358 static int portable_extract_by_path(
361 PortableMetadata
**ret_os_release
,
362 Hashmap
**ret_unit_files
,
363 sd_bus_error
*error
) {
365 _cleanup_(portable_metadata_hashmap_unrefp
) Hashmap
*unit_files
= NULL
;
366 _cleanup_(portable_metadata_unrefp
) PortableMetadata
* os_release
= NULL
;
367 _cleanup_(loop_device_unrefp
) LoopDevice
*d
= NULL
;
372 r
= loop_device_make_by_path(path
, O_RDONLY
, &d
);
374 /* We can't turn this into a loop-back block device, and this returns EISDIR? Then this is a directory
375 * tree and not a raw device. It's easy then. */
377 r
= extract_now(path
, matches
, -1, &os_release
, &unit_files
);
382 return log_debug_errno(r
, "Failed to set up loopback device: %m");
384 _cleanup_(dissected_image_unrefp
) DissectedImage
*m
= NULL
;
385 _cleanup_(rmdir_and_freep
) char *tmpdir
= NULL
;
386 _cleanup_(close_pairp
) int seq
[2] = { -1, -1 };
387 _cleanup_(sigkill_waitp
) pid_t child
= 0;
389 /* We now have a loopback block device, let's fork off a child in its own mount namespace, mount it
390 * there, and extract the metadata we need. The metadata is sent from the child back to us. */
392 BLOCK_SIGNALS(SIGCHLD
);
394 r
= mkdtemp_malloc("/tmp/inspect-XXXXXX", &tmpdir
);
396 return log_debug_errno(r
, "Failed to create temporary directory: %m");
398 r
= dissect_image(d
->fd
, NULL
, 0, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_REQUIRE_ROOT
|DISSECT_IMAGE_DISCARD_ON_LOOP
, &m
);
400 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't identify a suitable partition table or file system in '%s'.", path
);
401 else if (r
== -EADDRNOTAVAIL
)
402 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No root partition for specified root hash found in '%s'.", path
);
403 else if (r
== -ENOTUNIQ
)
404 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Multiple suitable root partitions found in image '%s'.", path
);
405 else if (r
== -ENXIO
)
406 sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "No suitable root partition found in image '%s'.", path
);
407 else if (r
== -EPROTONOSUPPORT
)
408 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
);
412 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, seq
) < 0)
413 return log_debug_errno(errno
, "Failed to allocated SOCK_SEQPACKET socket: %m");
415 r
= safe_fork("(sd-dissect)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_NEW_MOUNTNS
|FORK_MOUNTNS_SLAVE
|FORK_LOG
, &child
);
419 seq
[0] = safe_close(seq
[0]);
421 r
= dissected_image_mount(m
, tmpdir
, UID_INVALID
, DISSECT_IMAGE_READ_ONLY
|DISSECT_IMAGE_VALIDATE_OS
);
423 log_debug_errno(r
, "Failed to mount dissected image: %m");
427 r
= extract_now(tmpdir
, matches
, seq
[1], NULL
, NULL
);
430 _exit(r
< 0 ? EXIT_FAILURE
: EXIT_SUCCESS
);
433 seq
[1] = safe_close(seq
[1]);
435 unit_files
= hashmap_new(&string_hash_ops
);
440 _cleanup_(portable_metadata_unrefp
) PortableMetadata
*add
= NULL
;
441 _cleanup_free_
char *name
= NULL
;
442 _cleanup_close_
int fd
= -1;
444 r
= recv_item(seq
[0], &name
, &fd
);
446 return log_debug_errno(r
, "Failed to receive item: %m");
448 /* We can't really distuingish a zero-length datagram without any fds from EOF (both are signalled the
449 * same way by recvmsg()). Hence, accept either as end notification. */
450 if (isempty(name
) && fd
< 0)
453 if (isempty(name
) || fd
< 0) {
454 log_debug("Invalid item sent from child.");
458 add
= portable_metadata_new(name
, fd
);
463 /* Note that we do not initialize 'add->source' here, as the source path is not usable here as
464 * it refers to a path only valid in the short-living namespaced child process we forked
467 if (PORTABLE_METADATA_IS_UNIT(add
)) {
468 r
= hashmap_put(unit_files
, add
->name
, add
);
470 return log_debug_errno(r
, "Failed to add item to unit file list: %m");
474 } else if (PORTABLE_METADATA_IS_OS_RELEASE(add
)) {
477 os_release
= TAKE_PTR(add
);
479 assert_not_reached("Unexpected metadata item from child.");
482 r
= wait_for_terminate_and_check("(sd-dissect)", child
, 0);
489 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Image '%s' lacks os-release data, refusing.", path
);
491 if (hashmap_isempty(unit_files
))
492 return sd_bus_error_setf(error
, SD_BUS_ERROR_INVALID_ARGS
, "Couldn't find any matching unit files in image '%s', refusing.", path
);
495 *ret_unit_files
= TAKE_PTR(unit_files
);
498 *ret_os_release
= TAKE_PTR(os_release
);
503 int portable_extract(
504 const char *name_or_path
,
506 PortableMetadata
**ret_os_release
,
507 Hashmap
**ret_unit_files
,
508 sd_bus_error
*error
) {
510 _cleanup_(image_unrefp
) Image
*image
= NULL
;
513 assert(name_or_path
);
515 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, &image
);
519 return portable_extract_by_path(image
->path
, matches
, ret_os_release
, ret_unit_files
, error
);
522 static int unit_file_is_active(
525 sd_bus_error
*error
) {
527 static const char *const active_states
[] = {
539 /* If we are looking at a plain or instance things are easy, we can just query the state */
540 if (unit_name_is_valid(name
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
)) {
541 _cleanup_free_
char *path
= NULL
, *buf
= NULL
;
543 path
= unit_dbus_path_from_name(name
);
547 r
= sd_bus_get_property_string(
549 "org.freedesktop.systemd1",
551 "org.freedesktop.systemd1.Unit",
556 return log_debug_errno(r
, "Failed to retrieve unit state: %s", bus_error_message(error
, r
));
558 return strv_contains((char**) active_states
, buf
);
561 /* Otherwise we need to enumerate. But let's build the most restricted query we can */
562 if (unit_name_is_valid(name
, UNIT_NAME_TEMPLATE
)) {
563 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
564 const char *at
, *prefix
, *joined
;
566 r
= sd_bus_message_new_method_call(
569 "org.freedesktop.systemd1",
570 "/org/freedesktop/systemd1",
571 "org.freedesktop.systemd1.Manager",
572 "ListUnitsByPatterns");
576 r
= sd_bus_message_append_strv(m
, (char**) active_states
);
580 at
= strchr(name
, '@');
583 prefix
= strndupa(name
, at
+ 1 - name
);
584 joined
= strjoina(prefix
, "*", at
+ 1);
586 r
= sd_bus_message_append_strv(m
, STRV_MAKE(joined
));
590 r
= sd_bus_call(bus
, m
, 0, error
, &reply
);
592 return log_debug_errno(r
, "Failed to list units: %s", bus_error_message(error
, r
));
594 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_ARRAY
, "(ssssssouso)");
598 r
= sd_bus_message_enter_container(reply
, SD_BUS_TYPE_STRUCT
, "ssssssouso");
608 static int portable_changes_add(
609 PortableChange
**changes
,
611 PortableChangeType type
,
613 const char *source
) {
615 _cleanup_free_
char *p
= NULL
, *s
= NULL
;
619 assert(!changes
== !n_changes
);
624 c
= reallocarray(*changes
, *n_changes
+ 1, sizeof(PortableChange
));
633 path_simplify(p
, false);
640 path_simplify(s
, false);
643 c
[(*n_changes
)++] = (PortableChange
) {
646 .source
= TAKE_PTR(s
),
652 static int portable_changes_add_with_prefix(
653 PortableChange
**changes
,
655 PortableChangeType type
,
658 const char *source
) {
661 assert(!changes
== !n_changes
);
667 path
= strjoina(prefix
, "/", path
);
670 source
= strjoina(prefix
, "/", source
);
673 return portable_changes_add(changes
, n_changes
, type
, path
, source
);
676 void portable_changes_free(PortableChange
*changes
, size_t n_changes
) {
679 assert(changes
|| n_changes
== 0);
681 for (i
= 0; i
< n_changes
; i
++) {
682 free(changes
[i
].path
);
683 free(changes
[i
].source
);
689 static int install_chroot_dropin(
690 const char *image_path
,
692 const PortableMetadata
*m
,
693 const char *dropin_dir
,
695 PortableChange
**changes
,
698 _cleanup_free_
char *text
= NULL
, *dropin
= NULL
;
705 dropin
= strjoin(dropin_dir
, "/20-portable.conf");
709 text
= strjoin(PORTABLE_DROPIN_MARKER_BEGIN
, image_path
, PORTABLE_DROPIN_MARKER_END
"\n");
713 if (endswith(m
->name
, ".service"))
714 if (!strextend(&text
,
717 IN_SET(type
, IMAGE_DIRECTORY
, IMAGE_SUBVOLUME
) ? "RootDirectory=" : "RootImage=", image_path
, "\n"
718 "Environment=PORTABLE=", basename(image_path
), "\n"
719 "LogExtraFields=PORTABLE=", basename(image_path
), "\n",
724 r
= write_string_file(dropin
, text
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
726 return log_debug_errno(r
, "Failed to write '%s': %m", dropin
);
728 (void) portable_changes_add(changes
, n_changes
, PORTABLE_WRITE
, dropin
, NULL
);
731 *ret_dropin
= TAKE_PTR(dropin
);
736 static int find_profile(const char *name
, const char *unit
, char **ret
) {
742 assert_se(dot
= strrchr(unit
, '.'));
744 NULSTR_FOREACH(p
, profile_dirs
) {
745 _cleanup_free_
char *joined
;
747 joined
= strjoin(p
, "/", name
, "/", dot
+ 1, ".conf");
751 if (laccess(joined
, F_OK
) >= 0) {
752 *ret
= TAKE_PTR(joined
);
763 static int install_profile_dropin(
764 const char *image_path
,
765 const PortableMetadata
*m
,
766 const char *dropin_dir
,
770 PortableChange
**changes
,
773 _cleanup_free_
char *dropin
= NULL
, *from
= NULL
;
783 r
= find_profile(profile
, m
->name
, &from
);
786 return log_debug_errno(errno
, "Profile '%s' is not accessible: %m", profile
);
788 log_debug_errno(errno
, "Skipping link to profile '%s', as it does not exist: %m", profile
);
792 dropin
= strjoin(dropin_dir
, "/10-profile.conf");
796 if (flags
& PORTABLE_PREFER_COPY
) {
798 r
= copy_file_atomic(from
, dropin
, 0644, 0, COPY_REFLINK
);
800 return log_debug_errno(r
, "Failed to copy %s %s %s: %m", from
, special_glyph(ARROW
), dropin
);
802 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, dropin
, from
);
806 if (symlink(from
, dropin
) < 0)
807 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", from
, special_glyph(ARROW
), dropin
);
809 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, dropin
, from
);
813 *ret_dropin
= TAKE_PTR(dropin
);
818 static const char *attached_path(const LookupPaths
*paths
, PortableFlags flags
) {
823 if (flags
& PORTABLE_RUNTIME
)
824 where
= paths
->runtime_attached
;
826 where
= paths
->persistent_attached
;
832 static int attach_unit_file(
833 const LookupPaths
*paths
,
834 const char *image_path
,
836 const PortableMetadata
*m
,
839 PortableChange
**changes
,
842 _cleanup_(unlink_and_freep
) char *chroot_dropin
= NULL
, *profile_dropin
= NULL
;
843 _cleanup_(rmdir_and_freep
) char *dropin_dir
= NULL
;
844 const char *where
, *path
;
850 assert(PORTABLE_METADATA_IS_UNIT(m
));
852 where
= attached_path(paths
, flags
);
854 (void) mkdir_parents(where
, 0755);
855 if (mkdir(where
, 0755) < 0) {
859 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, where
, NULL
);
861 path
= strjoina(where
, "/", m
->name
);
862 dropin_dir
= strjoin(path
, ".d");
866 if (mkdir(dropin_dir
, 0755) < 0) {
870 (void) portable_changes_add(changes
, n_changes
, PORTABLE_MKDIR
, dropin_dir
, NULL
);
872 /* We install the drop-ins first, and the actual unit file last to achieve somewhat atomic behaviour if PID 1
873 * is reloaded while we are creating things here: as long as only the drop-ins exist the unit doesn't exist at
876 r
= install_chroot_dropin(image_path
, type
, m
, dropin_dir
, &chroot_dropin
, changes
, n_changes
);
880 r
= install_profile_dropin(image_path
, m
, dropin_dir
, profile
, flags
, &profile_dropin
, changes
, n_changes
);
884 if ((flags
& PORTABLE_PREFER_SYMLINK
) && m
->source
) {
886 if (symlink(m
->source
, path
) < 0)
887 return log_debug_errno(errno
, "Failed to symlink unit file '%s': %m", path
);
889 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, path
, m
->source
);
892 _cleanup_(unlink_and_freep
) char *tmp
= NULL
;
893 _cleanup_close_
int fd
= -1;
895 fd
= open_tmpfile_linkable(where
, O_WRONLY
|O_CLOEXEC
, &tmp
);
897 return log_debug_errno(fd
, "Failed to create unit file '%s': %m", path
);
899 r
= copy_bytes(m
->fd
, fd
, UINT64_MAX
, COPY_REFLINK
);
901 return log_debug_errno(r
, "Failed to copy unit file '%s': %m", path
);
903 if (fchmod(fd
, 0644) < 0)
904 return log_debug_errno(errno
, "Failed to change unit file access mode for '%s': %m", path
);
906 r
= link_tmpfile(fd
, tmp
, path
);
908 return log_debug_errno(r
, "Failed to install unit file '%s': %m", path
);
912 (void) portable_changes_add(changes
, n_changes
, PORTABLE_COPY
, path
, m
->source
);
915 /* All is established now, now let's disable any rollbacks */
916 chroot_dropin
= mfree(chroot_dropin
);
917 profile_dropin
= mfree(profile_dropin
);
918 dropin_dir
= mfree(dropin_dir
);
923 static int image_symlink(
924 const char *image_path
,
928 const char *fn
, *where
;
934 fn
= last_path_component(image_path
);
936 if (flags
& PORTABLE_RUNTIME
)
937 where
= "/run/portables/";
939 where
= "/etc/portables/";
941 joined
= strjoin(where
, fn
);
949 static int install_image_symlink(
950 const char *image_path
,
952 PortableChange
**changes
,
955 _cleanup_free_
char *sl
= NULL
;
960 /* If the image is outside of the image search also link it into it, so that it can be found with short image
961 * names and is listed among the images. */
963 if (image_in_search_path(IMAGE_PORTABLE
, image_path
))
966 r
= image_symlink(image_path
, flags
, &sl
);
968 return log_debug_errno(r
, "Failed to generate image symlink path: %m");
970 (void) mkdir_parents(sl
, 0755);
972 if (symlink(image_path
, sl
) < 0)
973 return log_debug_errno(errno
, "Failed to link %s %s %s: %m", image_path
, special_glyph(ARROW
), sl
);
975 (void) portable_changes_add(changes
, n_changes
, PORTABLE_SYMLINK
, sl
, image_path
);
981 const char *name_or_path
,
985 PortableChange
**changes
,
987 sd_bus_error
*error
) {
989 _cleanup_(portable_metadata_hashmap_unrefp
) Hashmap
*unit_files
= NULL
;
990 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
991 _cleanup_(image_unrefp
) Image
*image
= NULL
;
992 PortableMetadata
*item
;
996 assert(name_or_path
);
998 r
= image_find_harder(IMAGE_PORTABLE
, name_or_path
, &image
);
1002 r
= portable_extract_by_path(image
->path
, matches
, NULL
, &unit_files
, error
);
1006 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1010 HASHMAP_FOREACH(item
, unit_files
, iterator
) {
1011 r
= unit_file_exists(UNIT_FILE_SYSTEM
, &paths
, item
->name
);
1013 return sd_bus_error_set_errnof(error
, r
, "Failed to determine whether unit '%s' exists on the host: %m", item
->name
);
1015 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' exists on the host already, refusing.", item
->name
);
1017 r
= unit_file_is_active(bus
, item
->name
, error
);
1021 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active already, refusing.", item
->name
);
1024 HASHMAP_FOREACH(item
, unit_files
, iterator
) {
1025 r
= attach_unit_file(&paths
, image
->path
, image
->type
, item
, profile
, flags
, changes
, n_changes
);
1030 /* We don't care too much for the image symlink, it's just a convenience thing, it's not necessary for proper
1031 * operation otherwise. */
1032 (void) install_image_symlink(image
->path
, flags
, changes
, n_changes
);
1037 static bool marker_matches_image(const char *marker
, const char *name_or_path
) {
1041 assert(name_or_path
);
1043 a
= last_path_component(marker
);
1045 if (image_name_is_valid(name_or_path
)) {
1048 /* We shall match against an image name. In that case let's compare the last component, and optionally
1049 * allow either a suffix of ".raw" or a series of "/". */
1051 e
= startswith(a
, name_or_path
);
1056 e
[strspn(e
, "/")] == 0 ||
1062 /* We shall match against a path. Let's ignore any prefix here though, as often there are many ways to
1063 * reach the same file. However, in this mode, let's validate any file suffix. */
1065 l
= strcspn(a
, "/");
1066 b
= last_path_component(name_or_path
);
1068 if (strcspn(b
, "/") != l
)
1071 return memcmp(a
, b
, l
) == 0;
1075 static int test_chroot_dropin(
1079 const char *name_or_path
,
1080 char **ret_marker
) {
1082 _cleanup_free_
char *line
= NULL
, *marker
= NULL
;
1083 _cleanup_fclose_
FILE *f
= NULL
;
1084 _cleanup_close_
int fd
= -1;
1085 const char *p
, *e
, *k
;
1092 /* We recognize unis created from portable images via the drop-in we created for them */
1094 p
= strjoina(fname
, ".d/20-portable.conf");
1095 fd
= openat(dirfd(d
), p
, O_RDONLY
|O_CLOEXEC
);
1097 if (errno
== ENOENT
)
1100 return log_debug_errno(errno
, "Failed to open %s/%s: %m", where
, p
);
1103 f
= fdopen(fd
, "re");
1105 return log_debug_errno(errno
, "Failed to convert file handle: %m");
1108 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
1110 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1112 return log_debug_errno(r
, "Failed to read from %s/%s: %m", where
, p
);
1114 e
= startswith(line
, PORTABLE_DROPIN_MARKER_BEGIN
);
1118 k
= endswith(e
, PORTABLE_DROPIN_MARKER_END
);
1122 marker
= strndup(e
, k
- e
);
1129 r
= marker_matches_image(marker
, name_or_path
);
1132 *ret_marker
= TAKE_PTR(marker
);
1137 int portable_detach(
1139 const char *name_or_path
,
1140 PortableFlags flags
,
1141 PortableChange
**changes
,
1143 sd_bus_error
*error
) {
1145 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1146 _cleanup_set_free_free_ Set
*unit_files
= NULL
, *markers
= NULL
;
1147 _cleanup_closedir_
DIR *d
= NULL
;
1148 const char *where
, *item
;
1154 assert(name_or_path
);
1156 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1160 where
= attached_path(&paths
, flags
);
1164 if (errno
== ENOENT
)
1167 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1170 unit_files
= set_new(&string_hash_ops
);
1174 markers
= set_new(&path_hash_ops
);
1178 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1179 _cleanup_free_
char *marker
= NULL
;
1180 UnitFileState state
;
1182 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1185 /* Filter out duplicates */
1186 if (set_get(unit_files
, de
->d_name
))
1189 dirent_ensure_type(d
, de
);
1190 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1193 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, &marker
);
1199 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1201 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1202 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_RUNTIME
))
1203 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
));
1205 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1209 return sd_bus_error_setf(error
, BUS_ERROR_UNIT_EXISTS
, "Unit file '%s' is active, can't detach.", de
->d_name
);
1211 r
= set_put_strdup(unit_files
, de
->d_name
);
1213 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1215 if (path_is_absolute(marker
) &&
1216 !image_in_search_path(IMAGE_PORTABLE
, marker
)) {
1218 r
= set_ensure_allocated(&markers
, &path_hash_ops
);
1222 r
= set_put(markers
, marker
);
1225 else if (r
!= -EEXIST
)
1230 if (set_isempty(unit_files
))
1233 SET_FOREACH(item
, unit_files
, iterator
) {
1234 _cleanup_free_
char *md
= NULL
;
1237 if (unlinkat(dirfd(d
), item
, 0) < 0) {
1238 log_debug_errno(errno
, "Can't remove unit file %s/%s: %m", where
, item
);
1240 if (errno
!= ENOENT
&& ret
>= 0)
1243 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, item
, NULL
);
1245 FOREACH_STRING(suffix
, ".d/10-profile.conf", ".d/20-portable.conf") {
1246 _cleanup_free_
char *dropin
= NULL
;
1248 dropin
= strjoin(item
, suffix
);
1252 if (unlinkat(dirfd(d
), dropin
, 0) < 0) {
1253 log_debug_errno(errno
, "Can't remove drop-in %s/%s: %m", where
, dropin
);
1255 if (errno
!= ENOENT
&& ret
>= 0)
1258 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, dropin
, NULL
);
1261 md
= strjoin(item
, ".d");
1265 if (unlinkat(dirfd(d
), md
, AT_REMOVEDIR
) < 0) {
1266 log_debug_errno(errno
, "Can't remove drop-in directory %s/%s: %m", where
, md
);
1268 if (errno
!= ENOENT
&& ret
>= 0)
1271 portable_changes_add_with_prefix(changes
, n_changes
, PORTABLE_UNLINK
, where
, md
, NULL
);
1274 /* Now, also drop any image symlink, for images outside of the sarch path */
1275 SET_FOREACH(item
, markers
, iterator
) {
1276 _cleanup_free_
char *sl
= NULL
;
1279 r
= image_symlink(item
, flags
, &sl
);
1281 log_debug_errno(r
, "Failed to determine image symlink for '%s', ignoring: %m", item
);
1285 if (lstat(sl
, &st
) < 0) {
1286 log_debug_errno(errno
, "Failed to stat '%s', ignoring: %m", sl
);
1290 if (!S_ISLNK(st
.st_mode
)) {
1291 log_debug("Image '%s' is not a symlink, ignoring.", sl
);
1295 if (unlink(sl
) < 0) {
1296 log_debug_errno(errno
, "Can't remove image symlink '%s': %m", sl
);
1298 if (errno
!= ENOENT
&& ret
>= 0)
1301 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, sl
, NULL
);
1304 /* Try to remove the unit file directory, if we can */
1305 if (rmdir(where
) >= 0)
1306 portable_changes_add(changes
, n_changes
, PORTABLE_UNLINK
, where
, NULL
);
1311 log_debug("No unit files associated with '%s' found. Image not attached?", name_or_path
);
1312 return sd_bus_error_setf(error
, BUS_ERROR_NO_SUCH_UNIT
, "No unit files associated with '%s' found. Image not attached?", name_or_path
);
1315 static int portable_get_state_internal(
1317 const char *name_or_path
,
1318 PortableFlags flags
,
1320 sd_bus_error
*error
) {
1322 _cleanup_(lookup_paths_free
) LookupPaths paths
= {};
1323 bool found_enabled
= false, found_running
= false;
1324 _cleanup_set_free_free_ Set
*unit_files
= NULL
;
1325 _cleanup_closedir_
DIR *d
= NULL
;
1330 assert(name_or_path
);
1333 r
= lookup_paths_init(&paths
, UNIT_FILE_SYSTEM
, LOOKUP_PATHS_SPLIT_USR
, NULL
);
1337 where
= attached_path(&paths
, flags
);
1341 if (errno
== ENOENT
) {
1342 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1343 *ret
= PORTABLE_DETACHED
;
1347 return log_debug_errno(errno
, "Failed to open '%s' directory: %m", where
);
1350 unit_files
= set_new(&string_hash_ops
);
1354 FOREACH_DIRENT(de
, d
, return log_debug_errno(errno
, "Failed to enumerate '%s' directory: %m", where
)) {
1355 UnitFileState state
;
1357 if (!unit_name_is_valid(de
->d_name
, UNIT_NAME_ANY
))
1360 /* Filter out duplicates */
1361 if (set_get(unit_files
, de
->d_name
))
1364 dirent_ensure_type(d
, de
);
1365 if (!IN_SET(de
->d_type
, DT_LNK
, DT_REG
))
1368 r
= test_chroot_dropin(d
, where
, de
->d_name
, name_or_path
, NULL
);
1374 r
= unit_file_lookup_state(UNIT_FILE_SYSTEM
, &paths
, de
->d_name
, &state
);
1376 return log_debug_errno(r
, "Failed to determine unit file state of '%s': %m", de
->d_name
);
1377 if (!IN_SET(state
, UNIT_FILE_STATIC
, UNIT_FILE_DISABLED
, UNIT_FILE_LINKED
, UNIT_FILE_LINKED_RUNTIME
))
1378 found_enabled
= true;
1380 r
= unit_file_is_active(bus
, de
->d_name
, error
);
1384 found_running
= true;
1386 r
= set_put_strdup(unit_files
, de
->d_name
);
1388 return log_debug_errno(r
, "Failed to add unit name '%s' to set: %m", de
->d_name
);
1391 *ret
= found_running
? (!set_isempty(unit_files
) && (flags
& PORTABLE_RUNTIME
) ? PORTABLE_RUNNING_RUNTIME
: PORTABLE_RUNNING
) :
1392 found_enabled
? (flags
& PORTABLE_RUNTIME
? PORTABLE_ENABLED_RUNTIME
: PORTABLE_ENABLED
) :
1393 !set_isempty(unit_files
) ? (flags
& PORTABLE_RUNTIME
? PORTABLE_ATTACHED_RUNTIME
: PORTABLE_ATTACHED
) : PORTABLE_DETACHED
;
1398 int portable_get_state(
1400 const char *name_or_path
,
1401 PortableFlags flags
,
1403 sd_bus_error
*error
) {
1405 PortableState state
;
1408 assert(name_or_path
);
1411 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1412 * the latter only if we didn't find anything in the former. */
1414 r
= portable_get_state_internal(bus
, name_or_path
, flags
& ~PORTABLE_RUNTIME
, &state
, error
);
1418 if (state
== PORTABLE_DETACHED
) {
1419 r
= portable_get_state_internal(bus
, name_or_path
, flags
| PORTABLE_RUNTIME
, &state
, error
);
1428 int portable_get_profiles(char ***ret
) {
1431 return conf_files_list_nulstr(ret
, NULL
, NULL
, CONF_FILES_DIRECTORY
|CONF_FILES_BASENAME
|CONF_FILES_FILTER_MASKED
, profile_dirs
);
1434 static const char* const portable_change_type_table
[_PORTABLE_CHANGE_TYPE_MAX
] = {
1435 [PORTABLE_COPY
] = "copy",
1436 [PORTABLE_MKDIR
] = "mkdir",
1437 [PORTABLE_SYMLINK
] = "symlink",
1438 [PORTABLE_UNLINK
] = "unlink",
1439 [PORTABLE_WRITE
] = "write",
1442 DEFINE_STRING_TABLE_LOOKUP(portable_change_type
, PortableChangeType
);
1444 static const char* const portable_state_table
[_PORTABLE_STATE_MAX
] = {
1445 [PORTABLE_DETACHED
] = "detached",
1446 [PORTABLE_ATTACHED
] = "attached",
1447 [PORTABLE_ATTACHED_RUNTIME
] = "attached-runtime",
1448 [PORTABLE_ENABLED
] = "enabled",
1449 [PORTABLE_ENABLED_RUNTIME
] = "enabled-runtime",
1450 [PORTABLE_RUNNING
] = "running",
1451 [PORTABLE_RUNNING_RUNTIME
] = "running-runtime",
1454 DEFINE_STRING_TABLE_LOOKUP(portable_state
, PortableState
);