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