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