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