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