]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/portable/portable.c
Merge pull request #25500 from DaanDeMeyer/mcopy-skip-symlinks
[thirdparty/systemd.git] / src / portable / portable.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/loop.h>
4
5 #include "bus-common-errors.h"
6 #include "bus-error.h"
7 #include "chase-symlinks.h"
8 #include "conf-files.h"
9 #include "copy.h"
10 #include "data-fd-util.h"
11 #include "constants.h"
12 #include "dirent-util.h"
13 #include "discover-image.h"
14 #include "dissect-image.h"
15 #include "env-file.h"
16 #include "env-util.h"
17 #include "errno-list.h"
18 #include "escape.h"
19 #include "extension-release.h"
20 #include "fd-util.h"
21 #include "fileio.h"
22 #include "fs-util.h"
23 #include "install.h"
24 #include "io-util.h"
25 #include "locale-util.h"
26 #include "loop-util.h"
27 #include "mkdir.h"
28 #include "nulstr-util.h"
29 #include "os-util.h"
30 #include "path-lookup.h"
31 #include "portable.h"
32 #include "process-util.h"
33 #include "selinux-util.h"
34 #include "set.h"
35 #include "signal-util.h"
36 #include "socket-util.h"
37 #include "sort-util.h"
38 #include "string-table.h"
39 #include "strv.h"
40 #include "tmpfile-util.h"
41 #include "user-util.h"
42
43 /* Markers used in the first line of our 20-portable.conf unit file drop-in to determine, that a) the unit file was
44 * dropped there by the portable service logic and b) for which image it was dropped there. */
45 #define PORTABLE_DROPIN_MARKER_BEGIN "# Drop-in created for image '"
46 #define PORTABLE_DROPIN_MARKER_END "', do not edit."
47
48 static bool prefix_match(const char *unit, const char *prefix) {
49 const char *p;
50
51 p = startswith(unit, prefix);
52 if (!p)
53 return false;
54
55 /* Only respect prefixes followed by dash or dot or when there's a complete match */
56 return IN_SET(*p, '-', '.', '@', 0);
57 }
58
59 static bool unit_match(const char *unit, char **matches) {
60 const char *dot;
61
62 dot = strrchr(unit, '.');
63 if (!dot)
64 return false;
65
66 if (!STR_IN_SET(dot, ".service", ".socket", ".target", ".timer", ".path"))
67 return false;
68
69 /* Empty match expression means: everything */
70 if (strv_isempty(matches))
71 return true;
72
73 /* Otherwise, at least one needs to match */
74 STRV_FOREACH(i, matches)
75 if (prefix_match(unit, *i))
76 return true;
77
78 return false;
79 }
80
81 static PortableMetadata *portable_metadata_new(const char *name, const char *path, const char *selinux_label, int fd) {
82 PortableMetadata *m;
83
84 m = malloc0(offsetof(PortableMetadata, name) + strlen(name) + 1);
85 if (!m)
86 return NULL;
87
88 /* In case of a layered attach, we want to remember which image the unit came from */
89 if (path) {
90 m->image_path = strdup(path);
91 if (!m->image_path)
92 return mfree(m);
93 }
94
95 /* The metadata file might have SELinux labels, we need to carry them and reapply them */
96 if (!isempty(selinux_label)) {
97 m->selinux_label = strdup(selinux_label);
98 if (!m->selinux_label) {
99 free(m->image_path);
100 return mfree(m);
101 }
102 }
103
104 strcpy(m->name, name);
105 m->fd = fd;
106
107 return TAKE_PTR(m);
108 }
109
110 PortableMetadata *portable_metadata_unref(PortableMetadata *i) {
111 if (!i)
112 return NULL;
113
114 safe_close(i->fd);
115 free(i->source);
116 free(i->image_path);
117 free(i->selinux_label);
118
119 return mfree(i);
120 }
121
122 static int compare_metadata(PortableMetadata *const *x, PortableMetadata *const *y) {
123 return strcmp((*x)->name, (*y)->name);
124 }
125
126 int portable_metadata_hashmap_to_sorted_array(Hashmap *unit_files, PortableMetadata ***ret) {
127
128 _cleanup_free_ PortableMetadata **sorted = NULL;
129 PortableMetadata *item;
130 size_t k = 0;
131
132 sorted = new(PortableMetadata*, hashmap_size(unit_files));
133 if (!sorted)
134 return -ENOMEM;
135
136 HASHMAP_FOREACH(item, unit_files)
137 sorted[k++] = item;
138
139 assert(k == hashmap_size(unit_files));
140
141 typesafe_qsort(sorted, k, compare_metadata);
142
143 *ret = TAKE_PTR(sorted);
144 return 0;
145 }
146
147 static int send_one_fd_iov_with_data_fd(
148 int socket_fd,
149 const struct iovec *iov,
150 size_t iovlen,
151 int fd) {
152
153 _cleanup_close_ int data_fd = -1;
154
155 assert(iov || iovlen == 0);
156 assert(socket_fd >= 0);
157 assert(fd >= 0);
158
159 data_fd = copy_data_fd(fd);
160 if (data_fd < 0)
161 return data_fd;
162
163 return send_one_fd_iov(socket_fd, data_fd, iov, iovlen, 0);
164 }
165
166 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(portable_metadata_hash_ops, char, string_hash_func, string_compare_func,
167 PortableMetadata, portable_metadata_unref);
168
169 static int extract_now(
170 const char *where,
171 char **matches,
172 const char *image_name,
173 bool path_is_extension,
174 bool relax_extension_release_check,
175 int socket_fd,
176 PortableMetadata **ret_os_release,
177 Hashmap **ret_unit_files) {
178
179 _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
180 _cleanup_(portable_metadata_unrefp) PortableMetadata *os_release = NULL;
181 _cleanup_(lookup_paths_free) LookupPaths paths = {};
182 _cleanup_close_ int os_release_fd = -1;
183 _cleanup_free_ char *os_release_path = NULL;
184 const char *os_release_id;
185 int r;
186
187 /* Extracts the metadata from a directory tree 'where'. Extracts two kinds of information: the /etc/os-release
188 * data, and all unit files matching the specified expression. Note that this function is called in two very
189 * different but also similar contexts. When the tool gets invoked on a directory tree, we'll process it
190 * directly, and in-process, and thus can return the requested data directly, via 'ret_os_release' and
191 * 'ret_unit_files'. However, if the tool is invoked on a raw disk image — which needs to be mounted first — we
192 * are invoked in a child process with private mounts and then need to send the collected data to our
193 * parent. To handle both cases in one call this function also gets a 'socket_fd' parameter, which when >= 0 is
194 * used to send the data to the parent. */
195
196 assert(where);
197
198 /* First, find os-release/extension-release and send it upstream (or just save it). */
199 if (path_is_extension) {
200 os_release_id = strjoina("/usr/lib/extension-release.d/extension-release.", image_name);
201 r = open_extension_release(where, image_name, relax_extension_release_check, &os_release_path, &os_release_fd);
202 } else {
203 os_release_id = "/etc/os-release";
204 r = open_os_release(where, &os_release_path, &os_release_fd);
205 }
206 if (r < 0)
207 log_debug_errno(r,
208 "Couldn't acquire %s file, ignoring: %m",
209 path_is_extension ? "extension-release " : "os-release");
210 else {
211 if (socket_fd >= 0) {
212 struct iovec iov[] = {
213 IOVEC_MAKE_STRING(os_release_id),
214 IOVEC_MAKE((char *)"\0", sizeof(char)),
215 };
216
217 r = send_one_fd_iov_with_data_fd(socket_fd, iov, ELEMENTSOF(iov), os_release_fd);
218 if (r < 0)
219 return log_debug_errno(r, "Failed to send os-release file: %m");
220 }
221
222 if (ret_os_release) {
223 os_release = portable_metadata_new(os_release_id, NULL, NULL, os_release_fd);
224 if (!os_release)
225 return -ENOMEM;
226
227 os_release_fd = -1;
228 os_release->source = TAKE_PTR(os_release_path);
229 }
230 }
231
232 /* Then, send unit file data to the parent (or/and add it to the hashmap). For that we use our usual unit
233 * discovery logic. Note that we force looking inside of /lib/systemd/system/ for units too, as we mightbe
234 * compiled for a split-usr system but the image might be a legacy-usr one. */
235 r = lookup_paths_init(&paths, LOOKUP_SCOPE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, where);
236 if (r < 0)
237 return log_debug_errno(r, "Failed to acquire lookup paths: %m");
238
239 unit_files = hashmap_new(&portable_metadata_hash_ops);
240 if (!unit_files)
241 return -ENOMEM;
242
243 STRV_FOREACH(i, paths.search_path) {
244 _cleanup_free_ char *resolved = NULL;
245 _cleanup_closedir_ DIR *d = NULL;
246
247 r = chase_symlinks_and_opendir(*i, where, 0, &resolved, &d);
248 if (r < 0) {
249 log_debug_errno(r, "Failed to open unit path '%s', ignoring: %m", *i);
250 continue;
251 }
252
253 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to read directory: %m")) {
254 _cleanup_(portable_metadata_unrefp) PortableMetadata *m = NULL;
255 _cleanup_(mac_selinux_freep) char *con = NULL;
256 _cleanup_close_ int fd = -1;
257
258 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
259 continue;
260
261 if (!unit_match(de->d_name, matches))
262 continue;
263
264 /* Filter out duplicates */
265 if (hashmap_get(unit_files, de->d_name))
266 continue;
267
268 if (!IN_SET(de->d_type, DT_LNK, DT_REG))
269 continue;
270
271 fd = openat(dirfd(d), de->d_name, O_CLOEXEC|O_RDONLY);
272 if (fd < 0) {
273 log_debug_errno(errno, "Failed to open unit file '%s', ignoring: %m", de->d_name);
274 continue;
275 }
276
277 #if HAVE_SELINUX
278 /* The units will be copied on the host's filesystem, so if they had a SELinux label
279 * we have to preserve it. Copy it out so that it can be applied later. */
280
281 r = fgetfilecon_raw(fd, &con);
282 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(errno))
283 log_debug_errno(errno, "Failed to get SELinux file context from '%s', ignoring: %m", de->d_name);
284 #endif
285
286 if (socket_fd >= 0) {
287 struct iovec iov[] = {
288 IOVEC_MAKE_STRING(de->d_name),
289 IOVEC_MAKE((char *)"\0", sizeof(char)),
290 IOVEC_MAKE_STRING(strempty(con)),
291 };
292
293 r = send_one_fd_iov_with_data_fd(socket_fd, iov, ELEMENTSOF(iov), fd);
294 if (r < 0)
295 return log_debug_errno(r, "Failed to send unit metadata to parent: %m");
296 }
297
298 m = portable_metadata_new(de->d_name, where, con, fd);
299 if (!m)
300 return -ENOMEM;
301 fd = -1;
302
303 m->source = path_join(resolved, de->d_name);
304 if (!m->source)
305 return -ENOMEM;
306
307 r = hashmap_put(unit_files, m->name, m);
308 if (r < 0)
309 return log_debug_errno(r, "Failed to add unit to hashmap: %m");
310 m = NULL;
311 }
312 }
313
314 if (ret_os_release)
315 *ret_os_release = TAKE_PTR(os_release);
316 if (ret_unit_files)
317 *ret_unit_files = TAKE_PTR(unit_files);
318
319 return 0;
320 }
321
322 static int portable_extract_by_path(
323 const char *path,
324 bool path_is_extension,
325 bool relax_extension_release_check,
326 char **matches,
327 PortableMetadata **ret_os_release,
328 Hashmap **ret_unit_files,
329 sd_bus_error *error) {
330
331 _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
332 _cleanup_(portable_metadata_unrefp) PortableMetadata* os_release = NULL;
333 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
334 int r;
335
336 assert(path);
337
338 r = loop_device_make_by_path(path, O_RDONLY, LO_FLAGS_PARTSCAN, LOCK_SH, &d);
339 if (r == -EISDIR) {
340 _cleanup_free_ char *image_name = NULL;
341
342 /* We can't turn this into a loop-back block device, and this returns EISDIR? Then this is a directory
343 * tree and not a raw device. It's easy then. */
344
345 r = path_extract_filename(path, &image_name);
346 if (r < 0)
347 return log_error_errno(r, "Failed to extract image name from path '%s': %m", path);
348
349 r = extract_now(path, matches, image_name, path_is_extension, /* relax_extension_release_check= */ false, -1, &os_release, &unit_files);
350 if (r < 0)
351 return r;
352
353 } else if (r < 0)
354 return log_debug_errno(r, "Failed to set up loopback device for %s: %m", path);
355 else {
356 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
357 _cleanup_(rmdir_and_freep) char *tmpdir = NULL;
358 _cleanup_(close_pairp) int seq[2] = { -1, -1 };
359 _cleanup_(sigkill_waitp) pid_t child = 0;
360
361 /* We now have a loopback block device, let's fork off a child in its own mount namespace, mount it
362 * there, and extract the metadata we need. The metadata is sent from the child back to us. */
363
364 BLOCK_SIGNALS(SIGCHLD);
365
366 r = mkdtemp_malloc("/tmp/inspect-XXXXXX", &tmpdir);
367 if (r < 0)
368 return log_debug_errno(r, "Failed to create temporary directory: %m");
369
370 r = dissect_loop_device(
371 d,
372 NULL, NULL,
373 DISSECT_IMAGE_READ_ONLY |
374 DISSECT_IMAGE_GENERIC_ROOT |
375 DISSECT_IMAGE_REQUIRE_ROOT |
376 DISSECT_IMAGE_DISCARD_ON_LOOP |
377 DISSECT_IMAGE_RELAX_VAR_CHECK |
378 DISSECT_IMAGE_USR_NO_ROOT,
379 &m);
380 if (r == -ENOPKG)
381 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Couldn't identify a suitable partition table or file system in '%s'.", path);
382 else if (r == -EADDRNOTAVAIL)
383 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "No root partition for specified root hash found in '%s'.", path);
384 else if (r == -ENOTUNIQ)
385 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Multiple suitable root partitions found in image '%s'.", path);
386 else if (r == -ENXIO)
387 sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "No suitable root partition found in image '%s'.", path);
388 else if (r == -EPROTONOSUPPORT)
389 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);
390 if (r < 0)
391 return r;
392
393 if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, seq) < 0)
394 return log_debug_errno(errno, "Failed to allocated SOCK_SEQPACKET socket: %m");
395
396 r = safe_fork("(sd-dissect)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_NEW_MOUNTNS|FORK_MOUNTNS_SLAVE|FORK_LOG, &child);
397 if (r < 0)
398 return r;
399 if (r == 0) {
400 DissectImageFlags flags = DISSECT_IMAGE_READ_ONLY;
401
402 seq[0] = safe_close(seq[0]);
403
404 if (path_is_extension)
405 flags |= DISSECT_IMAGE_VALIDATE_OS_EXT | (relax_extension_release_check ? DISSECT_IMAGE_RELAX_SYSEXT_CHECK : 0);
406 else
407 flags |= DISSECT_IMAGE_VALIDATE_OS;
408
409 r = dissected_image_mount(m, tmpdir, UID_INVALID, UID_INVALID, flags);
410 if (r < 0) {
411 log_debug_errno(r, "Failed to mount dissected image: %m");
412 goto child_finish;
413 }
414
415 r = extract_now(tmpdir, matches, m->image_name, path_is_extension, relax_extension_release_check, seq[1], NULL, NULL);
416
417 child_finish:
418 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
419 }
420
421 seq[1] = safe_close(seq[1]);
422
423 unit_files = hashmap_new(&portable_metadata_hash_ops);
424 if (!unit_files)
425 return -ENOMEM;
426
427 for (;;) {
428 _cleanup_(portable_metadata_unrefp) PortableMetadata *add = NULL;
429 _cleanup_close_ int fd = -1;
430 /* We use NAME_MAX space for the SELinux label here. The kernel currently enforces no limit, but
431 * according to suggestions from the SELinux people this will change and it will probably be
432 * identical to NAME_MAX. For now we use that, but this should be updated one day when the final
433 * limit is known. */
434 char iov_buffer[PATH_MAX + NAME_MAX + 2];
435 struct iovec iov = IOVEC_INIT(iov_buffer, sizeof(iov_buffer));
436
437 ssize_t n = receive_one_fd_iov(seq[0], &iov, 1, 0, &fd);
438 if (n == -EIO)
439 break;
440 if (n < 0)
441 return log_debug_errno(n, "Failed to receive item: %m");
442 iov_buffer[n] = 0;
443
444 /* We can't really distinguish a zero-length datagram without any fds from EOF (both are signalled the
445 * same way by recvmsg()). Hence, accept either as end notification. */
446 if (isempty(iov_buffer) && fd < 0)
447 break;
448
449 if (isempty(iov_buffer) || fd < 0)
450 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
451 "Invalid item sent from child.");
452
453 /* Given recvmsg cannot be used with multiple io vectors if you don't know the size in advance,
454 * use a marker to separate the name and the optional SELinux context. */
455 char *selinux_label = memchr(iov_buffer, 0, n);
456 assert(selinux_label);
457 selinux_label++;
458
459 add = portable_metadata_new(iov_buffer, path, selinux_label, fd);
460 if (!add)
461 return -ENOMEM;
462 fd = -1;
463
464 /* Note that we do not initialize 'add->source' here, as the source path is not usable here as
465 * it refers to a path only valid in the short-living namespaced child process we forked
466 * here. */
467
468 if (PORTABLE_METADATA_IS_UNIT(add)) {
469 r = hashmap_put(unit_files, add->name, add);
470 if (r < 0)
471 return log_debug_errno(r, "Failed to add item to unit file list: %m");
472
473 add = NULL;
474
475 } else if (PORTABLE_METADATA_IS_OS_RELEASE(add) || PORTABLE_METADATA_IS_EXTENSION_RELEASE(add)) {
476
477 assert(!os_release);
478 os_release = TAKE_PTR(add);
479 } else
480 assert_not_reached();
481 }
482
483 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
484 if (r < 0)
485 return r;
486 child = 0;
487 }
488
489 if (!os_release)
490 return sd_bus_error_setf(error,
491 SD_BUS_ERROR_INVALID_ARGS,
492 "Image '%s' lacks %s data, refusing.",
493 path,
494 path_is_extension ? "extension-release" : "os-release");
495
496 if (ret_unit_files)
497 *ret_unit_files = TAKE_PTR(unit_files);
498
499 if (ret_os_release)
500 *ret_os_release = TAKE_PTR(os_release);
501
502 return 0;
503 }
504
505 static int extract_image_and_extensions(
506 const char *name_or_path,
507 char **matches,
508 char **extension_image_paths,
509 bool validate_sysext,
510 bool relax_extension_release_check,
511 Image **ret_image,
512 OrderedHashmap **ret_extension_images,
513 OrderedHashmap **ret_extension_releases,
514 PortableMetadata **ret_os_release,
515 Hashmap **ret_unit_files,
516 char ***ret_valid_prefixes,
517 sd_bus_error *error) {
518
519 _cleanup_free_ char *id = NULL, *version_id = NULL, *sysext_level = NULL;
520 _cleanup_(portable_metadata_unrefp) PortableMetadata *os_release = NULL;
521 _cleanup_ordered_hashmap_free_ OrderedHashmap *extension_images = NULL, *extension_releases = NULL;
522 _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
523 _cleanup_strv_free_ char **valid_prefixes = NULL;
524 _cleanup_(image_unrefp) Image *image = NULL;
525 Image *ext;
526 int r;
527
528 assert(name_or_path);
529
530 r = image_find_harder(IMAGE_PORTABLE, name_or_path, NULL, &image);
531 if (r < 0)
532 return r;
533
534 if (!strv_isempty(extension_image_paths)) {
535 extension_images = ordered_hashmap_new(&image_hash_ops);
536 if (!extension_images)
537 return -ENOMEM;
538
539 if (ret_extension_releases) {
540 extension_releases = ordered_hashmap_new(&portable_metadata_hash_ops);
541 if (!extension_releases)
542 return -ENOMEM;
543 }
544
545 STRV_FOREACH(p, extension_image_paths) {
546 _cleanup_(image_unrefp) Image *new = NULL;
547
548 r = image_find_harder(IMAGE_PORTABLE, *p, NULL, &new);
549 if (r < 0)
550 return r;
551
552 r = ordered_hashmap_put(extension_images, new->name, new);
553 if (r < 0)
554 return r;
555 TAKE_PTR(new);
556 }
557 }
558
559 r = portable_extract_by_path(image->path, /* path_is_extension= */ false, /* relax_extension_release_check= */ false, matches, &os_release, &unit_files, error);
560 if (r < 0)
561 return r;
562
563 /* If we are layering extension images on top of a runtime image, check that the os-release and
564 * extension-release metadata match, otherwise reject it immediately as invalid, or it will fail when
565 * the units are started. Also, collect valid portable prefixes if caller requested that. */
566 if (validate_sysext || ret_valid_prefixes) {
567 _cleanup_fclose_ FILE *f = NULL;
568 _cleanup_free_ char *prefixes = NULL;
569
570 r = take_fdopen_unlocked(&os_release->fd, "r", &f);
571 if (r < 0)
572 return r;
573
574 r = parse_env_file(f, os_release->name,
575 "ID", &id,
576 "VERSION_ID", &version_id,
577 "SYSEXT_LEVEL", &sysext_level,
578 "PORTABLE_PREFIXES", &prefixes);
579 if (r < 0)
580 return r;
581 if (isempty(id))
582 return sd_bus_error_set_errnof(error, SYNTHETIC_ERRNO(ESTALE), "Image %s os-release metadata lacks the ID field", name_or_path);
583
584 if (prefixes) {
585 valid_prefixes = strv_split(prefixes, WHITESPACE);
586 if (!valid_prefixes)
587 return -ENOMEM;
588 }
589 }
590
591 ORDERED_HASHMAP_FOREACH(ext, extension_images) {
592 _cleanup_(portable_metadata_unrefp) PortableMetadata *extension_release_meta = NULL;
593 _cleanup_hashmap_free_ Hashmap *extra_unit_files = NULL;
594 _cleanup_strv_free_ char **extension_release = NULL;
595 _cleanup_close_ int extension_release_fd = -1;
596 _cleanup_fclose_ FILE *f = NULL;
597 const char *e;
598
599 r = portable_extract_by_path(ext->path, /* path_is_extension= */ true, relax_extension_release_check, matches, &extension_release_meta, &extra_unit_files, error);
600 if (r < 0)
601 return r;
602
603 r = hashmap_move(unit_files, extra_unit_files);
604 if (r < 0)
605 return r;
606
607 if (!validate_sysext && !ret_valid_prefixes && !ret_extension_releases)
608 continue;
609
610 /* We need to keep the fd valid, to return the PortableMetadata to the caller. */
611 extension_release_fd = fd_reopen(extension_release_meta->fd, O_CLOEXEC|O_RDONLY);
612 if (extension_release_fd < 0)
613 return extension_release_fd;
614
615 r = take_fdopen_unlocked(&extension_release_fd, "r", &f);
616 if (r < 0)
617 return r;
618
619 r = load_env_file_pairs(f, extension_release_meta->name, &extension_release);
620 if (r < 0)
621 return r;
622
623 if (validate_sysext) {
624 r = extension_release_validate(ext->path, id, version_id, sysext_level, "portable", extension_release);
625 if (r == 0)
626 return sd_bus_error_set_errnof(error, SYNTHETIC_ERRNO(ESTALE), "Image %s extension-release metadata does not match the root's", ext->path);
627 if (r < 0)
628 return sd_bus_error_set_errnof(error, r, "Failed to compare image %s extension-release metadata with the root's os-release: %m", ext->path);
629 }
630
631 e = strv_env_pairs_get(extension_release, "PORTABLE_PREFIXES");
632 if (e) {
633 _cleanup_strv_free_ char **l = NULL;
634
635 l = strv_split(e, WHITESPACE);
636 if (!l)
637 return -ENOMEM;
638
639 r = strv_extend_strv(&valid_prefixes, l, true);
640 if (r < 0)
641 return r;
642 }
643
644 if (ret_extension_releases) {
645 r = ordered_hashmap_put(extension_releases, ext->name, extension_release_meta);
646 if (r < 0)
647 return r;
648 TAKE_PTR(extension_release_meta);
649 }
650 }
651
652 strv_sort(valid_prefixes);
653
654 if (ret_image)
655 *ret_image = TAKE_PTR(image);
656 if (ret_extension_images)
657 *ret_extension_images = TAKE_PTR(extension_images);
658 if (ret_extension_releases)
659 *ret_extension_releases = TAKE_PTR(extension_releases);
660 if (ret_os_release)
661 *ret_os_release = TAKE_PTR(os_release);
662 if (ret_unit_files)
663 *ret_unit_files = TAKE_PTR(unit_files);
664 if (ret_valid_prefixes)
665 *ret_valid_prefixes = TAKE_PTR(valid_prefixes);
666
667 return 0;
668 }
669
670 int portable_extract(
671 const char *name_or_path,
672 char **matches,
673 char **extension_image_paths,
674 PortableFlags flags,
675 PortableMetadata **ret_os_release,
676 OrderedHashmap **ret_extension_releases,
677 Hashmap **ret_unit_files,
678 char ***ret_valid_prefixes,
679 sd_bus_error *error) {
680
681 _cleanup_(portable_metadata_unrefp) PortableMetadata *os_release = NULL;
682 _cleanup_ordered_hashmap_free_ OrderedHashmap *extension_images = NULL, *extension_releases = NULL;
683 _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
684 _cleanup_(strv_freep) char **valid_prefixes = NULL;
685 _cleanup_(image_unrefp) Image *image = NULL;
686 int r;
687
688 assert(name_or_path);
689
690 r = extract_image_and_extensions(
691 name_or_path,
692 matches,
693 extension_image_paths,
694 /* validate_sysext= */ false,
695 /* relax_extension_release_check= */ FLAGS_SET(flags, PORTABLE_FORCE_SYSEXT),
696 &image,
697 &extension_images,
698 &extension_releases,
699 &os_release,
700 &unit_files,
701 ret_valid_prefixes ? &valid_prefixes : NULL,
702 error);
703 if (r < 0)
704 return r;
705
706 if (hashmap_isempty(unit_files)) {
707 _cleanup_free_ char *extensions = strv_join(extension_image_paths, ", ");
708 if (!extensions)
709 return -ENOMEM;
710
711 return sd_bus_error_setf(error,
712 SD_BUS_ERROR_INVALID_ARGS,
713 "Couldn't find any matching unit files in image '%s%s%s', refusing.",
714 image->path,
715 isempty(extensions) ? "" : "' or any of its extensions '",
716 isempty(extensions) ? "" : extensions);
717 }
718
719 if (ret_os_release)
720 *ret_os_release = TAKE_PTR(os_release);
721 if (ret_extension_releases)
722 *ret_extension_releases = TAKE_PTR(extension_releases);
723 if (ret_unit_files)
724 *ret_unit_files = TAKE_PTR(unit_files);
725 if (ret_valid_prefixes)
726 *ret_valid_prefixes = TAKE_PTR(valid_prefixes);
727
728 return 0;
729 }
730
731 static int unit_file_is_active(
732 sd_bus *bus,
733 const char *name,
734 sd_bus_error *error) {
735
736 static const char *const active_states[] = {
737 "activating",
738 "active",
739 "reloading",
740 "deactivating",
741 NULL,
742 };
743 int r;
744
745 if (!bus)
746 return false;
747
748 /* If we are looking at a plain or instance things are easy, we can just query the state */
749 if (unit_name_is_valid(name, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE)) {
750 _cleanup_free_ char *path = NULL, *buf = NULL;
751
752 path = unit_dbus_path_from_name(name);
753 if (!path)
754 return -ENOMEM;
755
756 r = sd_bus_get_property_string(
757 bus,
758 "org.freedesktop.systemd1",
759 path,
760 "org.freedesktop.systemd1.Unit",
761 "ActiveState",
762 error,
763 &buf);
764 if (r < 0)
765 return log_debug_errno(r, "Failed to retrieve unit state: %s", bus_error_message(error, r));
766
767 return strv_contains((char**) active_states, buf);
768 }
769
770 /* Otherwise we need to enumerate. But let's build the most restricted query we can */
771 if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
772 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
773 const char *at, *prefix, *joined;
774
775 r = sd_bus_message_new_method_call(
776 bus,
777 &m,
778 "org.freedesktop.systemd1",
779 "/org/freedesktop/systemd1",
780 "org.freedesktop.systemd1.Manager",
781 "ListUnitsByPatterns");
782 if (r < 0)
783 return r;
784
785 r = sd_bus_message_append_strv(m, (char**) active_states);
786 if (r < 0)
787 return r;
788
789 at = strchr(name, '@');
790 assert(at);
791
792 prefix = strndupa_safe(name, at + 1 - name);
793 joined = strjoina(prefix, "*", at + 1);
794
795 r = sd_bus_message_append_strv(m, STRV_MAKE(joined));
796 if (r < 0)
797 return r;
798
799 r = sd_bus_call(bus, m, 0, error, &reply);
800 if (r < 0)
801 return log_debug_errno(r, "Failed to list units: %s", bus_error_message(error, r));
802
803 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
804 if (r < 0)
805 return r;
806
807 r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_STRUCT, "ssssssouso");
808 if (r < 0)
809 return r;
810
811 return r > 0;
812 }
813
814 return -EINVAL;
815 }
816
817 static int portable_changes_add(
818 PortableChange **changes,
819 size_t *n_changes,
820 int type_or_errno, /* PORTABLE_COPY, PORTABLE_SYMLINK, … if positive, or errno if negative */
821 const char *path,
822 const char *source) {
823
824 _cleanup_free_ char *p = NULL, *s = NULL;
825 PortableChange *c;
826
827 assert(path);
828 assert(!changes == !n_changes);
829
830 if (type_or_errno >= 0)
831 assert(type_or_errno < _PORTABLE_CHANGE_TYPE_MAX);
832 else
833 assert(type_or_errno >= -ERRNO_MAX);
834
835 if (!changes)
836 return 0;
837
838 c = reallocarray(*changes, *n_changes + 1, sizeof(PortableChange));
839 if (!c)
840 return -ENOMEM;
841 *changes = c;
842
843 p = strdup(path);
844 if (!p)
845 return -ENOMEM;
846
847 path_simplify(p);
848
849 if (source) {
850 s = strdup(source);
851 if (!s)
852 return -ENOMEM;
853
854 path_simplify(s);
855 }
856
857 c[(*n_changes)++] = (PortableChange) {
858 .type_or_errno = type_or_errno,
859 .path = TAKE_PTR(p),
860 .source = TAKE_PTR(s),
861 };
862
863 return 0;
864 }
865
866 static int portable_changes_add_with_prefix(
867 PortableChange **changes,
868 size_t *n_changes,
869 int type_or_errno,
870 const char *prefix,
871 const char *path,
872 const char *source) {
873
874 _cleanup_free_ char *path_buf = NULL, *source_buf = NULL;
875
876 assert(path);
877 assert(!changes == !n_changes);
878
879 if (!changes)
880 return 0;
881
882 if (prefix) {
883 path_buf = path_join(prefix, path);
884 if (!path_buf)
885 return -ENOMEM;
886
887 path = path_buf;
888
889 if (source) {
890 source_buf = path_join(prefix, source);
891 if (!source_buf)
892 return -ENOMEM;
893
894 source = source_buf;
895 }
896 }
897
898 return portable_changes_add(changes, n_changes, type_or_errno, path, source);
899 }
900
901 void portable_changes_free(PortableChange *changes, size_t n_changes) {
902 size_t i;
903
904 assert(changes || n_changes == 0);
905
906 for (i = 0; i < n_changes; i++) {
907 free(changes[i].path);
908 free(changes[i].source);
909 }
910
911 free(changes);
912 }
913
914 static const char *root_setting_from_image(ImageType type) {
915 return IN_SET(type, IMAGE_DIRECTORY, IMAGE_SUBVOLUME) ? "RootDirectory=" : "RootImage=";
916 }
917
918 static const char *extension_setting_from_image(ImageType type) {
919 return IN_SET(type, IMAGE_DIRECTORY, IMAGE_SUBVOLUME) ? "ExtensionDirectories=" : "ExtensionImages=";
920 }
921
922 static int make_marker_text(const char *image_path, OrderedHashmap *extension_images, char **ret_text) {
923 _cleanup_free_ char *text = NULL, *escaped_image_path = NULL;
924 Image *ext;
925
926 assert(image_path);
927 assert(ret_text);
928
929 escaped_image_path = xescape(image_path, ":");
930 if (!escaped_image_path)
931 return -ENOMEM;
932
933 /* If the image is layered, include all layers in the marker as a colon-separated
934 * list of paths, so that we can do exact matches on removal. */
935 text = strjoin(PORTABLE_DROPIN_MARKER_BEGIN, escaped_image_path);
936 if (!text)
937 return -ENOMEM;
938
939 ORDERED_HASHMAP_FOREACH(ext, extension_images) {
940 _cleanup_free_ char *escaped = NULL;
941
942 escaped = xescape(ext->path, ":");
943 if (!escaped)
944 return -ENOMEM;
945
946 if (!strextend(&text, ":", escaped))
947 return -ENOMEM;
948 }
949
950 if (!strextend(&text, PORTABLE_DROPIN_MARKER_END "\n"))
951 return -ENOMEM;
952
953 *ret_text = TAKE_PTR(text);
954 return 0;
955 }
956
957 static int install_chroot_dropin(
958 const char *image_path,
959 ImageType type,
960 OrderedHashmap *extension_images,
961 const PortableMetadata *m,
962 const char *dropin_dir,
963 PortableFlags flags,
964 char **ret_dropin,
965 PortableChange **changes,
966 size_t *n_changes) {
967
968 _cleanup_free_ char *text = NULL, *dropin = NULL;
969 int r;
970
971 assert(image_path);
972 assert(m);
973 assert(dropin_dir);
974
975 dropin = path_join(dropin_dir, "20-portable.conf");
976 if (!dropin)
977 return -ENOMEM;
978
979 r = make_marker_text(image_path, extension_images, &text);
980 if (r < 0)
981 return log_debug_errno(r, "Failed to generate marker string for portable drop-in: %m");
982
983 if (endswith(m->name, ".service")) {
984 const char *os_release_source, *root_type;
985 _cleanup_free_ char *base_name = NULL;
986 Image *ext;
987
988 root_type = root_setting_from_image(type);
989
990 if (access("/etc/os-release", F_OK) < 0) {
991 if (errno != ENOENT)
992 return log_debug_errno(errno, "Failed to check if /etc/os-release exists: %m");
993
994 os_release_source = "/usr/lib/os-release";
995 } else
996 os_release_source = "/etc/os-release";
997
998 r = path_extract_filename(m->image_path ?: image_path, &base_name);
999 if (r < 0)
1000 return log_debug_errno(r, "Failed to extract basename from '%s': %m", m->image_path ?: image_path);
1001
1002 if (!strextend(&text,
1003 "\n"
1004 "[Service]\n",
1005 root_type, image_path, "\n"
1006 "Environment=PORTABLE=", base_name, "\n"
1007 "BindReadOnlyPaths=", os_release_source, ":/run/host/os-release\n"
1008 "LogExtraFields=PORTABLE=", base_name, "\n"))
1009 return -ENOMEM;
1010
1011 if (m->image_path && !path_equal(m->image_path, image_path))
1012 ORDERED_HASHMAP_FOREACH(ext, extension_images)
1013 if (!strextend(&text,
1014 extension_setting_from_image(ext->type),
1015 ext->path,
1016 /* With --force tell PID1 to avoid enforcing that the image <name> and
1017 * extension-release.<name> have to match. */
1018 !IN_SET(type, IMAGE_DIRECTORY, IMAGE_SUBVOLUME) &&
1019 FLAGS_SET(flags, PORTABLE_FORCE_SYSEXT) ?
1020 ":x-systemd.relax-extension-release-check" :
1021 "",
1022 "\n"))
1023 return -ENOMEM;
1024 }
1025
1026 r = write_string_file(dropin, text, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1027 if (r < 0)
1028 return log_debug_errno(r, "Failed to write '%s': %m", dropin);
1029
1030 (void) portable_changes_add(changes, n_changes, PORTABLE_WRITE, dropin, NULL);
1031
1032 if (ret_dropin)
1033 *ret_dropin = TAKE_PTR(dropin);
1034
1035 return 0;
1036 }
1037
1038 static int install_profile_dropin(
1039 const char *image_path,
1040 const PortableMetadata *m,
1041 const char *dropin_dir,
1042 const char *profile,
1043 PortableFlags flags,
1044 char **ret_dropin,
1045 PortableChange **changes,
1046 size_t *n_changes) {
1047
1048 _cleanup_free_ char *dropin = NULL, *from = NULL;
1049 int r;
1050
1051 assert(image_path);
1052 assert(m);
1053 assert(dropin_dir);
1054
1055 if (!profile)
1056 return 0;
1057
1058 r = find_portable_profile(profile, m->name, &from);
1059 if (r < 0) {
1060 if (r != -ENOENT)
1061 return log_debug_errno(errno, "Profile '%s' is not accessible: %m", profile);
1062
1063 log_debug_errno(errno, "Skipping link to profile '%s', as it does not exist: %m", profile);
1064 return 0;
1065 }
1066
1067 dropin = path_join(dropin_dir, "10-profile.conf");
1068 if (!dropin)
1069 return -ENOMEM;
1070
1071 if (flags & PORTABLE_PREFER_COPY) {
1072
1073 r = copy_file_atomic(from, dropin, 0644, 0, 0, COPY_REFLINK);
1074 if (r < 0)
1075 return log_debug_errno(r, "Failed to copy %s %s %s: %m", from, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), dropin);
1076
1077 (void) portable_changes_add(changes, n_changes, PORTABLE_COPY, dropin, from);
1078
1079 } else {
1080
1081 if (symlink(from, dropin) < 0)
1082 return log_debug_errno(errno, "Failed to link %s %s %s: %m", from, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), dropin);
1083
1084 (void) portable_changes_add(changes, n_changes, PORTABLE_SYMLINK, dropin, from);
1085 }
1086
1087 if (ret_dropin)
1088 *ret_dropin = TAKE_PTR(dropin);
1089
1090 return 0;
1091 }
1092
1093 static const char *attached_path(const LookupPaths *paths, PortableFlags flags) {
1094 const char *where;
1095
1096 assert(paths);
1097
1098 if (flags & PORTABLE_RUNTIME)
1099 where = paths->runtime_attached;
1100 else
1101 where = paths->persistent_attached;
1102
1103 assert(where);
1104 return where;
1105 }
1106
1107 static int attach_unit_file(
1108 const LookupPaths *paths,
1109 const char *image_path,
1110 ImageType type,
1111 OrderedHashmap *extension_images,
1112 const PortableMetadata *m,
1113 const char *profile,
1114 PortableFlags flags,
1115 PortableChange **changes,
1116 size_t *n_changes) {
1117
1118 _cleanup_(unlink_and_freep) char *chroot_dropin = NULL, *profile_dropin = NULL;
1119 _cleanup_(rmdir_and_freep) char *dropin_dir = NULL;
1120 _cleanup_free_ char *path = NULL;
1121 const char *where;
1122 int r;
1123
1124 assert(paths);
1125 assert(image_path);
1126 assert(m);
1127 assert(PORTABLE_METADATA_IS_UNIT(m));
1128
1129 where = attached_path(paths, flags);
1130
1131 (void) mkdir_parents(where, 0755);
1132 if (mkdir(where, 0755) < 0) {
1133 if (errno != EEXIST)
1134 return log_debug_errno(errno, "Failed to create attach directory %s: %m", where);
1135 } else
1136 (void) portable_changes_add(changes, n_changes, PORTABLE_MKDIR, where, NULL);
1137
1138 path = path_join(where, m->name);
1139 if (!path)
1140 return -ENOMEM;
1141
1142 dropin_dir = strjoin(path, ".d");
1143 if (!dropin_dir)
1144 return -ENOMEM;
1145
1146 if (mkdir(dropin_dir, 0755) < 0) {
1147 if (errno != EEXIST)
1148 return log_debug_errno(errno, "Failed to create drop-in directory %s: %m", dropin_dir);
1149 } else
1150 (void) portable_changes_add(changes, n_changes, PORTABLE_MKDIR, dropin_dir, NULL);
1151
1152 /* We install the drop-ins first, and the actual unit file last to achieve somewhat atomic behaviour if PID 1
1153 * is reloaded while we are creating things here: as long as only the drop-ins exist the unit doesn't exist at
1154 * all for PID 1. */
1155
1156 r = install_chroot_dropin(image_path, type, extension_images, m, dropin_dir, flags, &chroot_dropin, changes, n_changes);
1157 if (r < 0)
1158 return r;
1159
1160 r = install_profile_dropin(image_path, m, dropin_dir, profile, flags, &profile_dropin, changes, n_changes);
1161 if (r < 0)
1162 return r;
1163
1164 if ((flags & PORTABLE_PREFER_SYMLINK) && m->source) {
1165
1166 if (symlink(m->source, path) < 0)
1167 return log_debug_errno(errno, "Failed to symlink unit file '%s': %m", path);
1168
1169 (void) portable_changes_add(changes, n_changes, PORTABLE_SYMLINK, path, m->source);
1170
1171 } else {
1172 _cleanup_(unlink_and_freep) char *tmp = NULL;
1173 _cleanup_close_ int fd = -1;
1174
1175 (void) mac_selinux_create_file_prepare_label(path, m->selinux_label);
1176
1177 fd = open_tmpfile_linkable(path, O_WRONLY|O_CLOEXEC, &tmp);
1178 mac_selinux_create_file_clear(); /* Clear immediately in case of errors */
1179 if (fd < 0)
1180 return log_debug_errno(fd, "Failed to create unit file '%s': %m", path);
1181
1182 r = copy_bytes(m->fd, fd, UINT64_MAX, COPY_REFLINK);
1183 if (r < 0)
1184 return log_debug_errno(r, "Failed to copy unit file '%s': %m", path);
1185
1186 if (fchmod(fd, 0644) < 0)
1187 return log_debug_errno(errno, "Failed to change unit file access mode for '%s': %m", path);
1188
1189 r = link_tmpfile(fd, tmp, path);
1190 if (r < 0)
1191 return log_debug_errno(r, "Failed to install unit file '%s': %m", path);
1192
1193 tmp = mfree(tmp);
1194
1195 (void) portable_changes_add(changes, n_changes, PORTABLE_COPY, path, m->source);
1196 }
1197
1198 /* All is established now, now let's disable any rollbacks */
1199 chroot_dropin = mfree(chroot_dropin);
1200 profile_dropin = mfree(profile_dropin);
1201 dropin_dir = mfree(dropin_dir);
1202
1203 return 0;
1204 }
1205
1206 static int image_symlink(
1207 const char *image_path,
1208 PortableFlags flags,
1209 char **ret) {
1210
1211 const char *fn, *where;
1212 char *joined = NULL;
1213
1214 assert(image_path);
1215 assert(ret);
1216
1217 fn = last_path_component(image_path);
1218
1219 if (flags & PORTABLE_RUNTIME)
1220 where = "/run/portables/";
1221 else
1222 where = "/etc/portables/";
1223
1224 joined = strjoin(where, fn);
1225 if (!joined)
1226 return -ENOMEM;
1227
1228 *ret = joined;
1229 return 0;
1230 }
1231
1232 static int install_image_symlink(
1233 const char *image_path,
1234 PortableFlags flags,
1235 PortableChange **changes,
1236 size_t *n_changes) {
1237
1238 _cleanup_free_ char *sl = NULL;
1239 int r;
1240
1241 assert(image_path);
1242
1243 /* If the image is outside of the image search also link it into it, so that it can be found with short image
1244 * names and is listed among the images. */
1245
1246 if (image_in_search_path(IMAGE_PORTABLE, NULL, image_path))
1247 return 0;
1248
1249 r = image_symlink(image_path, flags, &sl);
1250 if (r < 0)
1251 return log_debug_errno(r, "Failed to generate image symlink path: %m");
1252
1253 (void) mkdir_parents(sl, 0755);
1254
1255 if (symlink(image_path, sl) < 0)
1256 return log_debug_errno(errno, "Failed to link %s %s %s: %m", image_path, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), sl);
1257
1258 (void) portable_changes_add(changes, n_changes, PORTABLE_SYMLINK, sl, image_path);
1259 return 0;
1260 }
1261
1262 static int install_image_and_extensions_symlinks(
1263 const Image *image,
1264 OrderedHashmap *extension_images,
1265 PortableFlags flags,
1266 PortableChange **changes,
1267 size_t *n_changes) {
1268
1269 Image *ext;
1270 int r;
1271
1272 assert(image);
1273
1274 ORDERED_HASHMAP_FOREACH(ext, extension_images) {
1275 r = install_image_symlink(ext->path, flags, changes, n_changes);
1276 if (r < 0)
1277 return r;
1278 }
1279
1280 r = install_image_symlink(image->path, flags, changes, n_changes);
1281 if (r < 0)
1282 return r;
1283
1284 return 0;
1285 }
1286
1287 static bool prefix_matches_compatible(char **matches, char **valid_prefixes) {
1288 /* Checks if all 'matches' are included in the list of 'valid_prefixes' */
1289
1290 STRV_FOREACH(m, matches)
1291 if (!strv_contains(valid_prefixes, *m))
1292 return false;
1293
1294 return true;
1295 }
1296
1297 int portable_attach(
1298 sd_bus *bus,
1299 const char *name_or_path,
1300 char **matches,
1301 const char *profile,
1302 char **extension_image_paths,
1303 PortableFlags flags,
1304 PortableChange **changes,
1305 size_t *n_changes,
1306 sd_bus_error *error) {
1307
1308 _cleanup_ordered_hashmap_free_ OrderedHashmap *extension_images = NULL;
1309 _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
1310 _cleanup_(lookup_paths_free) LookupPaths paths = {};
1311 _cleanup_strv_free_ char **valid_prefixes = NULL;
1312 _cleanup_(image_unrefp) Image *image = NULL;
1313 PortableMetadata *item;
1314 int r;
1315
1316 r = extract_image_and_extensions(
1317 name_or_path,
1318 matches,
1319 extension_image_paths,
1320 /* validate_sysext= */ true,
1321 /* relax_extension_release_check= */ FLAGS_SET(flags, PORTABLE_FORCE_SYSEXT),
1322 &image,
1323 &extension_images,
1324 /* extension_releases= */ NULL,
1325 /* os_release= */ NULL,
1326 &unit_files,
1327 &valid_prefixes,
1328 error);
1329 if (r < 0)
1330 return r;
1331
1332 if (valid_prefixes && !prefix_matches_compatible(matches, valid_prefixes)) {
1333 _cleanup_free_ char *matches_joined = NULL, *extensions_joined = NULL, *valid_prefixes_joined = NULL;
1334
1335 matches_joined = strv_join(matches, "', '");
1336 if (!matches_joined)
1337 return -ENOMEM;
1338
1339 extensions_joined = strv_join(extension_image_paths, ", ");
1340 if (!extensions_joined)
1341 return -ENOMEM;
1342
1343 valid_prefixes_joined = strv_join(valid_prefixes, ", ");
1344 if (!valid_prefixes_joined)
1345 return -ENOMEM;
1346
1347 return sd_bus_error_setf(
1348 error,
1349 SD_BUS_ERROR_INVALID_ARGS,
1350 "Selected matches '%s' are not compatible with portable service image '%s%s%s', refusing. (Acceptable prefix matches are: %s)",
1351 matches_joined,
1352 image->path,
1353 isempty(extensions_joined) ? "" : "' or any of its extensions '",
1354 strempty(extensions_joined),
1355 valid_prefixes_joined);
1356 }
1357
1358 if (hashmap_isempty(unit_files)) {
1359 _cleanup_free_ char *extensions_joined = strv_join(extension_image_paths, ", ");
1360 if (!extensions_joined)
1361 return -ENOMEM;
1362
1363 return sd_bus_error_setf(
1364 error,
1365 SD_BUS_ERROR_INVALID_ARGS,
1366 "Couldn't find any matching unit files in image '%s%s%s', refusing.",
1367 image->path,
1368 isempty(extensions_joined) ? "" : "' or any of its extensions '",
1369 strempty(extensions_joined));
1370 }
1371
1372 r = lookup_paths_init(&paths, LOOKUP_SCOPE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
1373 if (r < 0)
1374 return r;
1375
1376 if (!FLAGS_SET(flags, PORTABLE_REATTACH) && !FLAGS_SET(flags, PORTABLE_FORCE_ATTACH))
1377 HASHMAP_FOREACH(item, unit_files) {
1378 r = unit_file_exists(LOOKUP_SCOPE_SYSTEM, &paths, item->name);
1379 if (r < 0)
1380 return sd_bus_error_set_errnof(error, r, "Failed to determine whether unit '%s' exists on the host: %m", item->name);
1381 if (r > 0)
1382 return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' exists on the host already, refusing.", item->name);
1383
1384 r = unit_file_is_active(bus, item->name, error);
1385 if (r < 0)
1386 return r;
1387 if (r > 0)
1388 return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' is active already, refusing.", item->name);
1389 }
1390
1391 HASHMAP_FOREACH(item, unit_files) {
1392 r = attach_unit_file(&paths, image->path, image->type, extension_images,
1393 item, profile, flags, changes, n_changes);
1394 if (r < 0)
1395 return sd_bus_error_set_errnof(error, r, "Failed to attach unit '%s': %m", item->name);
1396 }
1397
1398 /* We don't care too much for the image symlink, it's just a convenience thing, it's not necessary for proper
1399 * operation otherwise. */
1400 (void) install_image_and_extensions_symlinks(image, extension_images, flags, changes, n_changes);
1401
1402 return 0;
1403 }
1404
1405 static bool marker_matches_images(const char *marker, const char *name_or_path, char **extension_image_paths) {
1406 _cleanup_strv_free_ char **root_and_extensions = NULL;
1407 const char *a;
1408 int r;
1409
1410 assert(marker);
1411 assert(name_or_path);
1412
1413 /* If extensions were used when attaching, the marker will be a colon-separated
1414 * list of images/paths. We enforce strict 1:1 matching, so that we are sure
1415 * we are detaching exactly what was attached.
1416 * For each image, starting with the root, we look for a token in the marker,
1417 * and return a negative answer on any non-matching combination. */
1418
1419 root_and_extensions = strv_new(name_or_path);
1420 if (!root_and_extensions)
1421 return -ENOMEM;
1422
1423 r = strv_extend_strv(&root_and_extensions, extension_image_paths, false);
1424 if (r < 0)
1425 return r;
1426
1427 STRV_FOREACH(image_name_or_path, root_and_extensions) {
1428 _cleanup_free_ char *image = NULL;
1429
1430 r = extract_first_word(&marker, &image, ":", EXTRACT_UNQUOTE|EXTRACT_RETAIN_ESCAPE);
1431 if (r < 0)
1432 return log_debug_errno(r, "Failed to parse marker: %s", marker);
1433 if (r == 0)
1434 return false;
1435
1436 a = last_path_component(image);
1437
1438 if (image_name_is_valid(*image_name_or_path)) {
1439 const char *e, *underscore;
1440
1441 /* We shall match against an image name. In that case let's compare the last component, and optionally
1442 * allow either a suffix of ".raw" or a series of "/".
1443 * But allow matching on a different version of the same image, when a "_" is used as a separator. */
1444 underscore = strchr(*image_name_or_path, '_');
1445 if (underscore) {
1446 if (strneq(a, *image_name_or_path, underscore - *image_name_or_path))
1447 continue;
1448 return false;
1449 }
1450
1451 e = startswith(a, *image_name_or_path);
1452 if (!e)
1453 return false;
1454
1455 if(!(e[strspn(e, "/")] == 0 || streq(e, ".raw")))
1456 return false;
1457 } else {
1458 const char *b, *underscore;
1459 size_t l;
1460
1461 /* We shall match against a path. Let's ignore any prefix here though, as often there are many ways to
1462 * reach the same file. However, in this mode, let's validate any file suffix.
1463 * But also ensure that we don't fail if both components don't have a '/' at all
1464 * (strcspn returns the full length of the string in that case, which might not
1465 * match as the versions might differ). */
1466
1467 l = strcspn(a, "/");
1468 b = last_path_component(*image_name_or_path);
1469
1470 if ((a[l] != '/') != !strchr(b, '/')) /* One is a directory, the other is not */
1471 return false;
1472
1473 if (a[l] != 0 && strcspn(b, "/") != l)
1474 return false;
1475
1476 underscore = strchr(b, '_');
1477 if (underscore)
1478 l = underscore - b;
1479 else { /* Either component could be versioned */
1480 underscore = strchr(a, '_');
1481 if (underscore)
1482 l = underscore - a;
1483 }
1484
1485 if (!strneq(a, b, l))
1486 return false;
1487 }
1488 }
1489
1490 return true;
1491 }
1492
1493 static int test_chroot_dropin(
1494 DIR *d,
1495 const char *where,
1496 const char *fname,
1497 const char *name_or_path,
1498 char **extension_image_paths,
1499 char **ret_marker) {
1500
1501 _cleanup_free_ char *line = NULL, *marker = NULL;
1502 _cleanup_fclose_ FILE *f = NULL;
1503 _cleanup_close_ int fd = -1;
1504 const char *p, *e, *k;
1505 int r;
1506
1507 assert(d);
1508 assert(where);
1509 assert(fname);
1510
1511 /* We recognize unis created from portable images via the drop-in we created for them */
1512
1513 p = strjoina(fname, ".d/20-portable.conf");
1514 fd = openat(dirfd(d), p, O_RDONLY|O_CLOEXEC);
1515 if (fd < 0) {
1516 if (errno == ENOENT)
1517 return 0;
1518
1519 return log_debug_errno(errno, "Failed to open %s/%s: %m", where, p);
1520 }
1521
1522 r = take_fdopen_unlocked(&fd, "r", &f);
1523 if (r < 0)
1524 return log_debug_errno(r, "Failed to convert file handle: %m");
1525
1526 r = read_line(f, LONG_LINE_MAX, &line);
1527 if (r < 0)
1528 return log_debug_errno(r, "Failed to read from %s/%s: %m", where, p);
1529
1530 e = startswith(line, PORTABLE_DROPIN_MARKER_BEGIN);
1531 if (!e)
1532 return 0;
1533
1534 k = endswith(e, PORTABLE_DROPIN_MARKER_END);
1535 if (!k)
1536 return 0;
1537
1538 marker = strndup(e, k - e);
1539 if (!marker)
1540 return -ENOMEM;
1541
1542 if (!name_or_path)
1543 r = true;
1544 else
1545 r = marker_matches_images(marker, name_or_path, extension_image_paths);
1546
1547 if (ret_marker)
1548 *ret_marker = TAKE_PTR(marker);
1549
1550 return r;
1551 }
1552
1553 int portable_detach(
1554 sd_bus *bus,
1555 const char *name_or_path,
1556 char **extension_image_paths,
1557 PortableFlags flags,
1558 PortableChange **changes,
1559 size_t *n_changes,
1560 sd_bus_error *error) {
1561
1562 _cleanup_(lookup_paths_free) LookupPaths paths = {};
1563 _cleanup_set_free_ Set *unit_files = NULL, *markers = NULL;
1564 _cleanup_free_ char *extensions = NULL;
1565 _cleanup_closedir_ DIR *d = NULL;
1566 const char *where, *item;
1567 int ret = 0;
1568 int r;
1569
1570 assert(name_or_path);
1571
1572 r = lookup_paths_init(&paths, LOOKUP_SCOPE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
1573 if (r < 0)
1574 return r;
1575
1576 where = attached_path(&paths, flags);
1577
1578 d = opendir(where);
1579 if (!d) {
1580 if (errno == ENOENT)
1581 goto not_found;
1582
1583 return log_debug_errno(errno, "Failed to open '%s' directory: %m", where);
1584 }
1585
1586 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to enumerate '%s' directory: %m", where)) {
1587 _cleanup_free_ char *marker = NULL, *unit_name = NULL;
1588 const char *dot;
1589
1590 /* When a portable service is enabled with "portablectl --copy=symlink --enable --now attach",
1591 * and is disabled with "portablectl --enable --now detach", which calls DisableUnitFilesWithFlags
1592 * DBus method, the main unit file is removed, but its drop-ins are not. Hence, here we need
1593 * to list both main unit files and drop-in directories (without the main unit files). */
1594
1595 dot = endswith(de->d_name, ".d");
1596 if (dot)
1597 unit_name = strndup(de->d_name, dot - de->d_name);
1598 else
1599 unit_name = strdup(de->d_name);
1600 if (!unit_name)
1601 return -ENOMEM;
1602
1603 if (!unit_name_is_valid(unit_name, UNIT_NAME_ANY))
1604 continue;
1605
1606 /* Filter out duplicates */
1607 if (set_contains(unit_files, unit_name))
1608 continue;
1609
1610 if (dot ? !IN_SET(de->d_type, DT_LNK, DT_DIR) : !IN_SET(de->d_type, DT_LNK, DT_REG))
1611 continue;
1612
1613 r = test_chroot_dropin(d, where, unit_name, name_or_path, extension_image_paths, &marker);
1614 if (r < 0)
1615 return r;
1616 if (r == 0)
1617 continue;
1618
1619 if (!FLAGS_SET(flags, PORTABLE_REATTACH) && !FLAGS_SET(flags, PORTABLE_FORCE_ATTACH)) {
1620 r = unit_file_is_active(bus, unit_name, error);
1621 if (r < 0)
1622 return r;
1623 if (r > 0)
1624 return sd_bus_error_setf(error, BUS_ERROR_UNIT_EXISTS, "Unit file '%s' is active, can't detach.", unit_name);
1625 }
1626
1627 r = set_ensure_consume(&unit_files, &string_hash_ops_free, TAKE_PTR(unit_name));
1628 if (r < 0)
1629 return log_oom_debug();
1630
1631 for (const char *p = marker;;) {
1632 _cleanup_free_ char *image = NULL;
1633
1634 r = extract_first_word(&p, &image, ":", EXTRACT_UNESCAPE_SEPARATORS|EXTRACT_RETAIN_ESCAPE);
1635 if (r < 0)
1636 return log_debug_errno(r, "Failed to parse marker: %s", p);
1637 if (r == 0)
1638 break;
1639
1640 if (path_is_absolute(image) && !image_in_search_path(IMAGE_PORTABLE, NULL, image)) {
1641 r = set_ensure_consume(&markers, &path_hash_ops_free, TAKE_PTR(image));
1642 if (r < 0)
1643 return r;
1644 }
1645 }
1646 }
1647
1648 if (set_isempty(unit_files))
1649 goto not_found;
1650
1651 SET_FOREACH(item, unit_files) {
1652 _cleanup_free_ char *md = NULL;
1653
1654 if (unlinkat(dirfd(d), item, 0) < 0) {
1655 log_debug_errno(errno, "Can't remove unit file %s/%s: %m", where, item);
1656
1657 if (errno != ENOENT && ret >= 0)
1658 ret = -errno;
1659 } else
1660 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, item, NULL);
1661
1662 FOREACH_STRING(suffix, ".d/10-profile.conf", ".d/20-portable.conf") {
1663 _cleanup_free_ char *dropin = NULL;
1664
1665 dropin = strjoin(item, suffix);
1666 if (!dropin)
1667 return -ENOMEM;
1668
1669 if (unlinkat(dirfd(d), dropin, 0) < 0) {
1670 log_debug_errno(errno, "Can't remove drop-in %s/%s: %m", where, dropin);
1671
1672 if (errno != ENOENT && ret >= 0)
1673 ret = -errno;
1674 } else
1675 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, dropin, NULL);
1676 }
1677
1678 md = strjoin(item, ".d");
1679 if (!md)
1680 return -ENOMEM;
1681
1682 if (unlinkat(dirfd(d), md, AT_REMOVEDIR) < 0) {
1683 log_debug_errno(errno, "Can't remove drop-in directory %s/%s: %m", where, md);
1684
1685 if (errno != ENOENT && ret >= 0)
1686 ret = -errno;
1687 } else
1688 portable_changes_add_with_prefix(changes, n_changes, PORTABLE_UNLINK, where, md, NULL);
1689 }
1690
1691 /* Now, also drop any image symlink, for images outside of the sarch path */
1692 SET_FOREACH(item, markers) {
1693 _cleanup_free_ char *sl = NULL;
1694 struct stat st;
1695
1696 r = image_symlink(item, flags, &sl);
1697 if (r < 0) {
1698 log_debug_errno(r, "Failed to determine image symlink for '%s', ignoring: %m", item);
1699 continue;
1700 }
1701
1702 if (lstat(sl, &st) < 0) {
1703 log_debug_errno(errno, "Failed to stat '%s', ignoring: %m", sl);
1704 continue;
1705 }
1706
1707 if (!S_ISLNK(st.st_mode)) {
1708 log_debug("Image '%s' is not a symlink, ignoring.", sl);
1709 continue;
1710 }
1711
1712 if (unlink(sl) < 0) {
1713 log_debug_errno(errno, "Can't remove image symlink '%s': %m", sl);
1714
1715 if (errno != ENOENT && ret >= 0)
1716 ret = -errno;
1717 } else
1718 portable_changes_add(changes, n_changes, PORTABLE_UNLINK, sl, NULL);
1719 }
1720
1721 /* Try to remove the unit file directory, if we can */
1722 if (rmdir(where) >= 0)
1723 portable_changes_add(changes, n_changes, PORTABLE_UNLINK, where, NULL);
1724
1725 return ret;
1726
1727 not_found:
1728 extensions = strv_join(extension_image_paths, ", ");
1729 if (!extensions)
1730 return -ENOMEM;
1731
1732 r = sd_bus_error_setf(error,
1733 BUS_ERROR_NO_SUCH_UNIT,
1734 "No unit files associated with '%s%s%s' found attached to the system. Image not attached?",
1735 name_or_path,
1736 isempty(extensions) ? "" : "' or any of its extensions '",
1737 isempty(extensions) ? "" : extensions);
1738 return log_debug_errno(r, "%s", error->message);
1739 }
1740
1741 static int portable_get_state_internal(
1742 sd_bus *bus,
1743 const char *name_or_path,
1744 char **extension_image_paths,
1745 PortableFlags flags,
1746 PortableState *ret,
1747 sd_bus_error *error) {
1748
1749 _cleanup_(lookup_paths_free) LookupPaths paths = {};
1750 bool found_enabled = false, found_running = false;
1751 _cleanup_set_free_ Set *unit_files = NULL;
1752 _cleanup_closedir_ DIR *d = NULL;
1753 const char *where;
1754 int r;
1755
1756 assert(name_or_path);
1757 assert(ret);
1758
1759 r = lookup_paths_init(&paths, LOOKUP_SCOPE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
1760 if (r < 0)
1761 return r;
1762
1763 where = attached_path(&paths, flags);
1764
1765 d = opendir(where);
1766 if (!d) {
1767 if (errno == ENOENT) {
1768 /* If the 'attached' directory doesn't exist at all, then we know for sure this image isn't attached. */
1769 *ret = PORTABLE_DETACHED;
1770 return 0;
1771 }
1772
1773 return log_debug_errno(errno, "Failed to open '%s' directory: %m", where);
1774 }
1775
1776 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to enumerate '%s' directory: %m", where)) {
1777 UnitFileState state;
1778
1779 if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
1780 continue;
1781
1782 /* Filter out duplicates */
1783 if (set_contains(unit_files, de->d_name))
1784 continue;
1785
1786 if (!IN_SET(de->d_type, DT_LNK, DT_REG))
1787 continue;
1788
1789 r = test_chroot_dropin(d, where, de->d_name, name_or_path, extension_image_paths, NULL);
1790 if (r < 0)
1791 return r;
1792 if (r == 0)
1793 continue;
1794
1795 r = unit_file_lookup_state(LOOKUP_SCOPE_SYSTEM, &paths, de->d_name, &state);
1796 if (r < 0)
1797 return log_debug_errno(r, "Failed to determine unit file state of '%s': %m", de->d_name);
1798 if (!IN_SET(state, UNIT_FILE_STATIC, UNIT_FILE_DISABLED, UNIT_FILE_LINKED, UNIT_FILE_LINKED_RUNTIME))
1799 found_enabled = true;
1800
1801 r = unit_file_is_active(bus, de->d_name, error);
1802 if (r < 0)
1803 return r;
1804 if (r > 0)
1805 found_running = true;
1806
1807 r = set_put_strdup(&unit_files, de->d_name);
1808 if (r < 0)
1809 return log_debug_errno(r, "Failed to add unit name '%s' to set: %m", de->d_name);
1810 }
1811
1812 *ret = found_running ? (!set_isempty(unit_files) && (flags & PORTABLE_RUNTIME) ? PORTABLE_RUNNING_RUNTIME : PORTABLE_RUNNING) :
1813 found_enabled ? (flags & PORTABLE_RUNTIME ? PORTABLE_ENABLED_RUNTIME : PORTABLE_ENABLED) :
1814 !set_isempty(unit_files) ? (flags & PORTABLE_RUNTIME ? PORTABLE_ATTACHED_RUNTIME : PORTABLE_ATTACHED) : PORTABLE_DETACHED;
1815
1816 return 0;
1817 }
1818
1819 int portable_get_state(
1820 sd_bus *bus,
1821 const char *name_or_path,
1822 char **extension_image_paths,
1823 PortableFlags flags,
1824 PortableState *ret,
1825 sd_bus_error *error) {
1826
1827 PortableState state;
1828 int r;
1829
1830 assert(name_or_path);
1831 assert(ret);
1832
1833 /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
1834 * the latter only if we didn't find anything in the former. */
1835
1836 r = portable_get_state_internal(bus, name_or_path, extension_image_paths, flags & ~PORTABLE_RUNTIME, &state, error);
1837 if (r < 0)
1838 return r;
1839
1840 if (state == PORTABLE_DETACHED) {
1841 r = portable_get_state_internal(bus, name_or_path, extension_image_paths, flags | PORTABLE_RUNTIME, &state, error);
1842 if (r < 0)
1843 return r;
1844 }
1845
1846 *ret = state;
1847 return 0;
1848 }
1849
1850 int portable_get_profiles(char ***ret) {
1851 assert(ret);
1852
1853 return conf_files_list_nulstr(ret, NULL, NULL, CONF_FILES_DIRECTORY|CONF_FILES_BASENAME|CONF_FILES_FILTER_MASKED, PORTABLE_PROFILE_DIRS);
1854 }
1855
1856 static const char* const portable_change_type_table[_PORTABLE_CHANGE_TYPE_MAX] = {
1857 [PORTABLE_COPY] = "copy",
1858 [PORTABLE_MKDIR] = "mkdir",
1859 [PORTABLE_SYMLINK] = "symlink",
1860 [PORTABLE_UNLINK] = "unlink",
1861 [PORTABLE_WRITE] = "write",
1862 };
1863
1864 DEFINE_STRING_TABLE_LOOKUP(portable_change_type, int);
1865
1866 static const char* const portable_state_table[_PORTABLE_STATE_MAX] = {
1867 [PORTABLE_DETACHED] = "detached",
1868 [PORTABLE_ATTACHED] = "attached",
1869 [PORTABLE_ATTACHED_RUNTIME] = "attached-runtime",
1870 [PORTABLE_ENABLED] = "enabled",
1871 [PORTABLE_ENABLED_RUNTIME] = "enabled-runtime",
1872 [PORTABLE_RUNNING] = "running",
1873 [PORTABLE_RUNNING_RUNTIME] = "running-runtime",
1874 };
1875
1876 DEFINE_STRING_TABLE_LOOKUP(portable_state, PortableState);