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