]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/discover-image.c
tree-wide: hook up image dissection policy logic everywhere
[thirdparty/systemd.git] / src / shared / discover-image.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <linux/fs.h>
6 #include <linux/loop.h>
7 #include <linux/magic.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <sys/file.h>
11 #include <sys/ioctl.h>
12 #include <sys/stat.h>
13 #include <unistd.h>
14
15 #include "alloc-util.h"
16 #include "btrfs-util.h"
17 #include "chase.h"
18 #include "chattr-util.h"
19 #include "copy.h"
20 #include "dirent-util.h"
21 #include "discover-image.h"
22 #include "dissect-image.h"
23 #include "env-file.h"
24 #include "env-util.h"
25 #include "extension-util.h"
26 #include "fd-util.h"
27 #include "fs-util.h"
28 #include "hashmap.h"
29 #include "hostname-setup.h"
30 #include "id128-util.h"
31 #include "lock-util.h"
32 #include "log.h"
33 #include "loop-util.h"
34 #include "macro.h"
35 #include "mkdir.h"
36 #include "nulstr-util.h"
37 #include "os-util.h"
38 #include "path-util.h"
39 #include "rm-rf.h"
40 #include "stat-util.h"
41 #include "string-table.h"
42 #include "string-util.h"
43 #include "strv.h"
44 #include "time-util.h"
45 #include "utf8.h"
46 #include "xattr-util.h"
47
48 static const char* const image_search_path[_IMAGE_CLASS_MAX] = {
49 [IMAGE_MACHINE] = "/etc/machines\0" /* only place symlinks here */
50 "/run/machines\0" /* and here too */
51 "/var/lib/machines\0" /* the main place for images */
52 "/var/lib/container\0" /* legacy */
53 "/usr/local/lib/machines\0"
54 "/usr/lib/machines\0",
55
56 [IMAGE_PORTABLE] = "/etc/portables\0" /* only place symlinks here */
57 "/run/portables\0" /* and here too */
58 "/var/lib/portables\0" /* the main place for images */
59 "/usr/local/lib/portables\0"
60 "/usr/lib/portables\0",
61
62 /* Note that we don't allow storing extensions under /usr/, unlike with other image types. That's
63 * because extension images are supposed to extend /usr/, so you get into recursive races, especially
64 * with directory-based extensions, as the kernel's OverlayFS explicitly checks for this and errors
65 * out with -ELOOP if it finds that a lowerdir= is a child of another lowerdir=. */
66 [IMAGE_EXTENSION] = "/etc/extensions\0" /* only place symlinks here */
67 "/run/extensions\0" /* and here too */
68 "/var/lib/extensions\0", /* the main place for images */
69 };
70
71 static Image *image_free(Image *i) {
72 assert(i);
73
74 free(i->name);
75 free(i->path);
76
77 free(i->hostname);
78 strv_free(i->machine_info);
79 strv_free(i->os_release);
80 strv_free(i->extension_release);
81
82 return mfree(i);
83 }
84
85 DEFINE_TRIVIAL_REF_UNREF_FUNC(Image, image, image_free);
86 DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(image_hash_ops, char, string_hash_func, string_compare_func,
87 Image, image_unref);
88
89 static char **image_settings_path(Image *image) {
90 _cleanup_strv_free_ char **l = NULL;
91 _cleanup_free_ char *fn = NULL;
92 size_t i = 0;
93 int r;
94
95 assert(image);
96
97 l = new0(char*, 4);
98 if (!l)
99 return NULL;
100
101 fn = strjoin(image->name, ".nspawn");
102 if (!fn)
103 return NULL;
104
105 FOREACH_STRING(s, "/etc/systemd/nspawn", "/run/systemd/nspawn") {
106 l[i] = path_join(s, fn);
107 if (!l[i])
108 return NULL;
109
110 i++;
111 }
112
113 r = file_in_same_dir(image->path, fn, l + i);
114 if (r == -ENOMEM)
115 return NULL;
116 if (r < 0)
117 log_debug_errno(r, "Failed to generate .nspawn settings path from image path, ignoring: %m");
118
119 strv_uniq(l);
120
121 return TAKE_PTR(l);
122 }
123
124 static int image_roothash_path(Image *image, char **ret) {
125 _cleanup_free_ char *fn = NULL;
126
127 assert(image);
128
129 fn = strjoin(image->name, ".roothash");
130 if (!fn)
131 return -ENOMEM;
132
133 return file_in_same_dir(image->path, fn, ret);
134 }
135
136 static int image_new(
137 ImageType t,
138 ImageClass c,
139 const char *pretty,
140 const char *path,
141 const char *filename,
142 bool read_only,
143 usec_t crtime,
144 usec_t mtime,
145 Image **ret) {
146
147 _cleanup_(image_unrefp) Image *i = NULL;
148
149 assert(t >= 0);
150 assert(t < _IMAGE_TYPE_MAX);
151 assert(pretty);
152 assert(filename);
153 assert(ret);
154
155 i = new(Image, 1);
156 if (!i)
157 return -ENOMEM;
158
159 *i = (Image) {
160 .n_ref = 1,
161 .type = t,
162 .class = c,
163 .read_only = read_only,
164 .crtime = crtime,
165 .mtime = mtime,
166 .usage = UINT64_MAX,
167 .usage_exclusive = UINT64_MAX,
168 .limit = UINT64_MAX,
169 .limit_exclusive = UINT64_MAX,
170 };
171
172 i->name = strdup(pretty);
173 if (!i->name)
174 return -ENOMEM;
175
176 i->path = path_join(path, filename);
177 if (!i->path)
178 return -ENOMEM;
179
180 path_simplify(i->path);
181
182 *ret = TAKE_PTR(i);
183
184 return 0;
185 }
186
187 static int extract_pretty(const char *path, const char *suffix, char **ret) {
188 _cleanup_free_ char *name = NULL;
189 const char *p;
190
191 assert(path);
192 assert(ret);
193
194 p = last_path_component(path);
195
196 name = strdupcspn(p, "/");
197 if (!name)
198 return -ENOMEM;
199
200 if (suffix) {
201 char *e;
202
203 e = endswith(name, suffix);
204 if (!e)
205 return -EINVAL;
206
207 *e = 0;
208 }
209
210 if (!image_name_is_valid(name))
211 return -EINVAL;
212
213 *ret = TAKE_PTR(name);
214 return 0;
215 }
216
217 static int image_make(
218 ImageClass c,
219 const char *pretty,
220 int dfd,
221 const char *path,
222 const char *filename,
223 const struct stat *st,
224 Image **ret) {
225
226 _cleanup_free_ char *pretty_buffer = NULL, *parent = NULL;
227 struct stat stbuf;
228 bool read_only;
229 int r;
230
231 assert(dfd >= 0 || dfd == AT_FDCWD);
232 assert(path || dfd == AT_FDCWD);
233 assert(filename);
234
235 /* We explicitly *do* follow symlinks here, since we want to allow symlinking trees, raw files and block
236 * devices into /var/lib/machines/, and treat them normally.
237 *
238 * This function returns -ENOENT if we can't find the image after all, and -EMEDIUMTYPE if it's not a file we
239 * recognize. */
240
241 if (!st) {
242 if (fstatat(dfd, filename, &stbuf, 0) < 0)
243 return -errno;
244
245 st = &stbuf;
246 }
247
248 if (!path) {
249 if (dfd == AT_FDCWD)
250 (void) safe_getcwd(&parent);
251 else
252 (void) fd_get_path(dfd, &parent);
253 }
254
255 read_only =
256 (path && path_startswith(path, "/usr")) ||
257 (faccessat(dfd, filename, W_OK, AT_EACCESS) < 0 && errno == EROFS);
258
259 if (S_ISDIR(st->st_mode)) {
260 _cleanup_close_ int fd = -EBADF;
261 unsigned file_attr = 0;
262 usec_t crtime = 0;
263
264 if (!ret)
265 return 0;
266
267 if (!pretty) {
268 r = extract_pretty(filename, NULL, &pretty_buffer);
269 if (r < 0)
270 return r;
271
272 pretty = pretty_buffer;
273 }
274
275 fd = openat(dfd, filename, O_CLOEXEC|O_NOCTTY|O_DIRECTORY);
276 if (fd < 0)
277 return -errno;
278
279 if (btrfs_might_be_subvol(st)) {
280
281 r = fd_is_fs_type(fd, BTRFS_SUPER_MAGIC);
282 if (r < 0)
283 return r;
284 if (r) {
285 BtrfsSubvolInfo info;
286
287 /* It's a btrfs subvolume */
288
289 r = btrfs_subvol_get_info_fd(fd, 0, &info);
290 if (r < 0)
291 return r;
292
293 r = image_new(IMAGE_SUBVOLUME,
294 c,
295 pretty,
296 path,
297 filename,
298 info.read_only || read_only,
299 info.otime,
300 0,
301 ret);
302 if (r < 0)
303 return r;
304
305 if (btrfs_quota_scan_ongoing(fd) == 0) {
306 BtrfsQuotaInfo quota;
307
308 r = btrfs_subvol_get_subtree_quota_fd(fd, 0, &quota);
309 if (r >= 0) {
310 (*ret)->usage = quota.referenced;
311 (*ret)->usage_exclusive = quota.exclusive;
312
313 (*ret)->limit = quota.referenced_max;
314 (*ret)->limit_exclusive = quota.exclusive_max;
315 }
316 }
317
318 return 0;
319 }
320 }
321
322 /* Get directory creation time (not available everywhere, but that's OK */
323 (void) fd_getcrtime(fd, &crtime);
324
325 /* If the IMMUTABLE bit is set, we consider the directory read-only. Since the ioctl is not
326 * supported everywhere we ignore failures. */
327 (void) read_attr_fd(fd, &file_attr);
328
329 /* It's just a normal directory. */
330 r = image_new(IMAGE_DIRECTORY,
331 c,
332 pretty,
333 path,
334 filename,
335 read_only || (file_attr & FS_IMMUTABLE_FL),
336 crtime,
337 0, /* we don't use mtime of stat() here, since it's not the time of last change of the tree, but only of the top-level dir */
338 ret);
339 if (r < 0)
340 return r;
341
342 return 0;
343
344 } else if (S_ISREG(st->st_mode) && endswith(filename, ".raw")) {
345 usec_t crtime = 0;
346
347 /* It's a RAW disk image */
348
349 if (!ret)
350 return 0;
351
352 (void) fd_getcrtime_at(dfd, filename, AT_SYMLINK_FOLLOW, &crtime);
353
354 if (!pretty) {
355 r = extract_pretty(filename, ".raw", &pretty_buffer);
356 if (r < 0)
357 return r;
358
359 pretty = pretty_buffer;
360 }
361
362 r = image_new(IMAGE_RAW,
363 c,
364 pretty,
365 path,
366 filename,
367 !(st->st_mode & 0222) || read_only,
368 crtime,
369 timespec_load(&st->st_mtim),
370 ret);
371 if (r < 0)
372 return r;
373
374 (*ret)->usage = (*ret)->usage_exclusive = st->st_blocks * 512;
375 (*ret)->limit = (*ret)->limit_exclusive = st->st_size;
376
377 return 0;
378
379 } else if (S_ISBLK(st->st_mode)) {
380 _cleanup_close_ int block_fd = -EBADF;
381 uint64_t size = UINT64_MAX;
382
383 /* A block device */
384
385 if (!ret)
386 return 0;
387
388 if (!pretty) {
389 r = extract_pretty(filename, NULL, &pretty_buffer);
390 if (r < 0)
391 return r;
392
393 pretty = pretty_buffer;
394 }
395
396 block_fd = openat(dfd, filename, O_RDONLY|O_NONBLOCK|O_CLOEXEC|O_NOCTTY);
397 if (block_fd < 0)
398 log_debug_errno(errno, "Failed to open block device %s/%s, ignoring: %m", path ?: strnull(parent), filename);
399 else {
400 /* Refresh stat data after opening the node */
401 if (fstat(block_fd, &stbuf) < 0)
402 return -errno;
403 st = &stbuf;
404
405 if (!S_ISBLK(st->st_mode)) /* Verify that what we opened is actually what we think it is */
406 return -ENOTTY;
407
408 if (!read_only) {
409 int state = 0;
410
411 if (ioctl(block_fd, BLKROGET, &state) < 0)
412 log_debug_errno(errno, "Failed to issue BLKROGET on device %s/%s, ignoring: %m", path ?: strnull(parent), filename);
413 else if (state)
414 read_only = true;
415 }
416
417 if (ioctl(block_fd, BLKGETSIZE64, &size) < 0)
418 log_debug_errno(errno, "Failed to issue BLKGETSIZE64 on device %s/%s, ignoring: %m", path ?: strnull(parent), filename);
419
420 block_fd = safe_close(block_fd);
421 }
422
423 r = image_new(IMAGE_BLOCK,
424 c,
425 pretty,
426 path,
427 filename,
428 !(st->st_mode & 0222) || read_only,
429 0,
430 0,
431 ret);
432 if (r < 0)
433 return r;
434
435 if (!IN_SET(size, 0, UINT64_MAX))
436 (*ret)->usage = (*ret)->usage_exclusive = (*ret)->limit = (*ret)->limit_exclusive = size;
437
438 return 0;
439 }
440
441 return -EMEDIUMTYPE;
442 }
443
444 int image_find(ImageClass class,
445 const char *name,
446 const char *root,
447 Image **ret) {
448
449 int r;
450
451 assert(class >= 0);
452 assert(class < _IMAGE_CLASS_MAX);
453 assert(name);
454
455 /* There are no images with invalid names */
456 if (!image_name_is_valid(name))
457 return -ENOENT;
458
459 NULSTR_FOREACH(path, image_search_path[class]) {
460 _cleanup_free_ char *resolved = NULL;
461 _cleanup_closedir_ DIR *d = NULL;
462 struct stat st;
463 int flags;
464
465 r = chase_and_opendir(path, root, CHASE_PREFIX_ROOT, &resolved, &d);
466 if (r == -ENOENT)
467 continue;
468 if (r < 0)
469 return r;
470
471 /* As mentioned above, we follow symlinks on this fstatat(), because we want to permit people
472 * to symlink block devices into the search path. (For now, we disable that when operating
473 * relative to some root directory.) */
474 flags = root ? AT_SYMLINK_NOFOLLOW : 0;
475 if (fstatat(dirfd(d), name, &st, flags) < 0) {
476 _cleanup_free_ char *raw = NULL;
477
478 if (errno != ENOENT)
479 return -errno;
480
481 raw = strjoin(name, ".raw");
482 if (!raw)
483 return -ENOMEM;
484
485 if (fstatat(dirfd(d), raw, &st, flags) < 0) {
486 if (errno == ENOENT)
487 continue;
488
489 return -errno;
490 }
491
492 if (!S_ISREG(st.st_mode))
493 continue;
494
495 r = image_make(class, name, dirfd(d), resolved, raw, &st, ret);
496
497 } else {
498 if (!S_ISDIR(st.st_mode) && !S_ISBLK(st.st_mode))
499 continue;
500
501 r = image_make(class, name, dirfd(d), resolved, name, &st, ret);
502 }
503 if (IN_SET(r, -ENOENT, -EMEDIUMTYPE))
504 continue;
505 if (r < 0)
506 return r;
507
508 if (ret)
509 (*ret)->discoverable = true;
510
511 return 1;
512 }
513
514 if (class == IMAGE_MACHINE && streq(name, ".host")) {
515 r = image_make(class, ".host", AT_FDCWD, NULL, empty_to_root(root), NULL, ret);
516 if (r < 0)
517 return r;
518
519 if (ret)
520 (*ret)->discoverable = true;
521
522 return r;
523 }
524
525 return -ENOENT;
526 };
527
528 int image_from_path(const char *path, Image **ret) {
529
530 /* Note that we don't set the 'discoverable' field of the returned object, because we don't check here whether
531 * the image is in the image search path. And if it is we don't know if the path we used is actually not
532 * overridden by another, different image earlier in the search path */
533
534 if (path_equal(path, "/"))
535 return image_make(IMAGE_MACHINE, ".host", AT_FDCWD, NULL, "/", NULL, ret);
536
537 return image_make(_IMAGE_CLASS_INVALID, NULL, AT_FDCWD, NULL, path, NULL, ret);
538 }
539
540 int image_find_harder(ImageClass class, const char *name_or_path, const char *root, Image **ret) {
541 if (image_name_is_valid(name_or_path))
542 return image_find(class, name_or_path, root, ret);
543
544 return image_from_path(name_or_path, ret);
545 }
546
547 int image_discover(
548 ImageClass class,
549 const char *root,
550 Hashmap *h) {
551
552 int r;
553
554 assert(class >= 0);
555 assert(class < _IMAGE_CLASS_MAX);
556 assert(h);
557
558 NULSTR_FOREACH(path, image_search_path[class]) {
559 _cleanup_free_ char *resolved = NULL;
560 _cleanup_closedir_ DIR *d = NULL;
561
562 r = chase_and_opendir(path, root, CHASE_PREFIX_ROOT, &resolved, &d);
563 if (r == -ENOENT)
564 continue;
565 if (r < 0)
566 return r;
567
568 FOREACH_DIRENT_ALL(de, d, return -errno) {
569 _cleanup_(image_unrefp) Image *image = NULL;
570 _cleanup_free_ char *truncated = NULL;
571 const char *pretty;
572 struct stat st;
573 int flags;
574
575 if (dot_or_dot_dot(de->d_name))
576 continue;
577
578 /* As mentioned above, we follow symlinks on this fstatat(), because we want to
579 * permit people to symlink block devices into the search path. */
580 flags = root ? AT_SYMLINK_NOFOLLOW : 0;
581 if (fstatat(dirfd(d), de->d_name, &st, flags) < 0) {
582 if (errno == ENOENT)
583 continue;
584
585 return -errno;
586 }
587
588 if (S_ISREG(st.st_mode)) {
589 const char *e;
590
591 e = endswith(de->d_name, ".raw");
592 if (!e)
593 continue;
594
595 truncated = strndup(de->d_name, e - de->d_name);
596 if (!truncated)
597 return -ENOMEM;
598
599 pretty = truncated;
600 } else if (S_ISDIR(st.st_mode) || S_ISBLK(st.st_mode))
601 pretty = de->d_name;
602 else
603 continue;
604
605 if (!image_name_is_valid(pretty))
606 continue;
607
608 if (hashmap_contains(h, pretty))
609 continue;
610
611 r = image_make(class, pretty, dirfd(d), resolved, de->d_name, &st, &image);
612 if (IN_SET(r, -ENOENT, -EMEDIUMTYPE))
613 continue;
614 if (r < 0)
615 return r;
616
617 image->discoverable = true;
618
619 r = hashmap_put(h, image->name, image);
620 if (r < 0)
621 return r;
622
623 image = NULL;
624 }
625 }
626
627 if (class == IMAGE_MACHINE && !hashmap_contains(h, ".host")) {
628 _cleanup_(image_unrefp) Image *image = NULL;
629
630 r = image_make(IMAGE_MACHINE, ".host", AT_FDCWD, NULL, empty_to_root("/"), NULL, &image);
631 if (r < 0)
632 return r;
633
634 image->discoverable = true;
635
636 r = hashmap_put(h, image->name, image);
637 if (r < 0)
638 return r;
639
640 image = NULL;
641 }
642
643 return 0;
644 }
645
646 int image_remove(Image *i) {
647 _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
648 _cleanup_strv_free_ char **settings = NULL;
649 _cleanup_free_ char *roothash = NULL;
650 int r;
651
652 assert(i);
653
654 if (IMAGE_IS_VENDOR(i) || IMAGE_IS_HOST(i))
655 return -EROFS;
656
657 settings = image_settings_path(i);
658 if (!settings)
659 return -ENOMEM;
660
661 r = image_roothash_path(i, &roothash);
662 if (r < 0)
663 return r;
664
665 /* Make sure we don't interfere with a running nspawn */
666 r = image_path_lock(i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
667 if (r < 0)
668 return r;
669
670 switch (i->type) {
671
672 case IMAGE_SUBVOLUME:
673
674 /* Let's unlink first, maybe it is a symlink? If that works we are happy. Otherwise, let's get out the
675 * big guns */
676 if (unlink(i->path) < 0) {
677 r = btrfs_subvol_remove(i->path, BTRFS_REMOVE_RECURSIVE|BTRFS_REMOVE_QUOTA);
678 if (r < 0)
679 return r;
680 }
681
682 break;
683
684 case IMAGE_DIRECTORY:
685 /* Allow deletion of read-only directories */
686 (void) chattr_path(i->path, 0, FS_IMMUTABLE_FL, NULL);
687 r = rm_rf(i->path, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME);
688 if (r < 0)
689 return r;
690
691 break;
692
693 case IMAGE_BLOCK:
694
695 /* If this is inside of /dev, then it's a real block device, hence let's not touch the device node
696 * itself (but let's remove the stuff stored alongside it). If it's anywhere else, let's try to unlink
697 * the thing (it's most likely a symlink after all). */
698
699 if (path_startswith(i->path, "/dev"))
700 break;
701
702 _fallthrough_;
703 case IMAGE_RAW:
704 if (unlink(i->path) < 0)
705 return -errno;
706 break;
707
708 default:
709 return -EOPNOTSUPP;
710 }
711
712 STRV_FOREACH(j, settings)
713 if (unlink(*j) < 0 && errno != ENOENT)
714 log_debug_errno(errno, "Failed to unlink %s, ignoring: %m", *j);
715
716 if (unlink(roothash) < 0 && errno != ENOENT)
717 log_debug_errno(errno, "Failed to unlink %s, ignoring: %m", roothash);
718
719 return 0;
720 }
721
722 static int rename_auxiliary_file(const char *path, const char *new_name, const char *suffix) {
723 _cleanup_free_ char *fn = NULL, *rs = NULL;
724 int r;
725
726 fn = strjoin(new_name, suffix);
727 if (!fn)
728 return -ENOMEM;
729
730 r = file_in_same_dir(path, fn, &rs);
731 if (r < 0)
732 return r;
733
734 return rename_noreplace(AT_FDCWD, path, AT_FDCWD, rs);
735 }
736
737 int image_rename(Image *i, const char *new_name) {
738 _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT, name_lock = LOCK_FILE_INIT;
739 _cleanup_free_ char *new_path = NULL, *nn = NULL, *roothash = NULL;
740 _cleanup_strv_free_ char **settings = NULL;
741 unsigned file_attr = 0;
742 int r;
743
744 assert(i);
745
746 if (!image_name_is_valid(new_name))
747 return -EINVAL;
748
749 if (IMAGE_IS_VENDOR(i) || IMAGE_IS_HOST(i))
750 return -EROFS;
751
752 settings = image_settings_path(i);
753 if (!settings)
754 return -ENOMEM;
755
756 r = image_roothash_path(i, &roothash);
757 if (r < 0)
758 return r;
759
760 /* Make sure we don't interfere with a running nspawn */
761 r = image_path_lock(i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
762 if (r < 0)
763 return r;
764
765 /* Make sure nobody takes the new name, between the time we
766 * checked it is currently unused in all search paths, and the
767 * time we take possession of it */
768 r = image_name_lock(new_name, LOCK_EX|LOCK_NB, &name_lock);
769 if (r < 0)
770 return r;
771
772 r = image_find(IMAGE_MACHINE, new_name, NULL, NULL);
773 if (r >= 0)
774 return -EEXIST;
775 if (r != -ENOENT)
776 return r;
777
778 switch (i->type) {
779
780 case IMAGE_DIRECTORY:
781 /* Turn of the immutable bit while we rename the image, so that we can rename it */
782 (void) read_attr_path(i->path, &file_attr);
783
784 if (file_attr & FS_IMMUTABLE_FL)
785 (void) chattr_path(i->path, 0, FS_IMMUTABLE_FL, NULL);
786
787 _fallthrough_;
788 case IMAGE_SUBVOLUME:
789 r = file_in_same_dir(i->path, new_name, &new_path);
790 break;
791
792 case IMAGE_BLOCK:
793
794 /* Refuse renaming raw block devices in /dev, the names are picked by udev after all. */
795 if (path_startswith(i->path, "/dev"))
796 return -EROFS;
797
798 r = file_in_same_dir(i->path, new_name, &new_path);
799 break;
800
801 case IMAGE_RAW: {
802 const char *fn;
803
804 fn = strjoina(new_name, ".raw");
805
806 r = file_in_same_dir(i->path, fn, &new_path);
807 break;
808 }
809
810 default:
811 return -EOPNOTSUPP;
812 }
813 if (r < 0)
814 return r;
815
816 nn = strdup(new_name);
817 if (!nn)
818 return -ENOMEM;
819
820 r = rename_noreplace(AT_FDCWD, i->path, AT_FDCWD, new_path);
821 if (r < 0)
822 return r;
823
824 /* Restore the immutable bit, if it was set before */
825 if (file_attr & FS_IMMUTABLE_FL)
826 (void) chattr_path(new_path, FS_IMMUTABLE_FL, FS_IMMUTABLE_FL, NULL);
827
828 free_and_replace(i->path, new_path);
829 free_and_replace(i->name, nn);
830
831 STRV_FOREACH(j, settings) {
832 r = rename_auxiliary_file(*j, new_name, ".nspawn");
833 if (r < 0 && r != -ENOENT)
834 log_debug_errno(r, "Failed to rename settings file %s, ignoring: %m", *j);
835 }
836
837 r = rename_auxiliary_file(roothash, new_name, ".roothash");
838 if (r < 0 && r != -ENOENT)
839 log_debug_errno(r, "Failed to rename roothash file %s, ignoring: %m", roothash);
840
841 return 0;
842 }
843
844 static int clone_auxiliary_file(const char *path, const char *new_name, const char *suffix) {
845 _cleanup_free_ char *fn = NULL, *rs = NULL;
846 int r;
847
848 fn = strjoin(new_name, suffix);
849 if (!fn)
850 return -ENOMEM;
851
852 r = file_in_same_dir(path, fn, &rs);
853 if (r < 0)
854 return r;
855
856 return copy_file_atomic(path, rs, 0664, COPY_REFLINK);
857 }
858
859 int image_clone(Image *i, const char *new_name, bool read_only) {
860 _cleanup_(release_lock_file) LockFile name_lock = LOCK_FILE_INIT;
861 _cleanup_strv_free_ char **settings = NULL;
862 _cleanup_free_ char *roothash = NULL;
863 const char *new_path;
864 int r;
865
866 assert(i);
867
868 if (!image_name_is_valid(new_name))
869 return -EINVAL;
870
871 settings = image_settings_path(i);
872 if (!settings)
873 return -ENOMEM;
874
875 r = image_roothash_path(i, &roothash);
876 if (r < 0)
877 return r;
878
879 /* Make sure nobody takes the new name, between the time we
880 * checked it is currently unused in all search paths, and the
881 * time we take possession of it */
882 r = image_name_lock(new_name, LOCK_EX|LOCK_NB, &name_lock);
883 if (r < 0)
884 return r;
885
886 r = image_find(IMAGE_MACHINE, new_name, NULL, NULL);
887 if (r >= 0)
888 return -EEXIST;
889 if (r != -ENOENT)
890 return r;
891
892 switch (i->type) {
893
894 case IMAGE_SUBVOLUME:
895 case IMAGE_DIRECTORY:
896 /* If we can we'll always try to create a new btrfs subvolume here, even if the source is a plain
897 * directory. */
898
899 new_path = strjoina("/var/lib/machines/", new_name);
900
901 r = btrfs_subvol_snapshot(i->path, new_path,
902 (read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) |
903 BTRFS_SNAPSHOT_FALLBACK_COPY |
904 BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
905 BTRFS_SNAPSHOT_FALLBACK_IMMUTABLE |
906 BTRFS_SNAPSHOT_RECURSIVE |
907 BTRFS_SNAPSHOT_QUOTA);
908 if (r >= 0)
909 /* Enable "subtree" quotas for the copy, if we didn't copy any quota from the source. */
910 (void) btrfs_subvol_auto_qgroup(new_path, 0, true);
911
912 break;
913
914 case IMAGE_RAW:
915 new_path = strjoina("/var/lib/machines/", new_name, ".raw");
916
917 r = copy_file_atomic_full(i->path, new_path, read_only ? 0444 : 0644, FS_NOCOW_FL, FS_NOCOW_FL,
918 COPY_REFLINK|COPY_CRTIME, NULL, NULL);
919 break;
920
921 case IMAGE_BLOCK:
922 default:
923 return -EOPNOTSUPP;
924 }
925
926 if (r < 0)
927 return r;
928
929 STRV_FOREACH(j, settings) {
930 r = clone_auxiliary_file(*j, new_name, ".nspawn");
931 if (r < 0 && r != -ENOENT)
932 log_debug_errno(r, "Failed to clone settings %s, ignoring: %m", *j);
933 }
934
935 r = clone_auxiliary_file(roothash, new_name, ".roothash");
936 if (r < 0 && r != -ENOENT)
937 log_debug_errno(r, "Failed to clone root hash file %s, ignoring: %m", roothash);
938
939 return 0;
940 }
941
942 int image_read_only(Image *i, bool b) {
943 _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
944 int r;
945
946 assert(i);
947
948 if (IMAGE_IS_VENDOR(i) || IMAGE_IS_HOST(i))
949 return -EROFS;
950
951 /* Make sure we don't interfere with a running nspawn */
952 r = image_path_lock(i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
953 if (r < 0)
954 return r;
955
956 switch (i->type) {
957
958 case IMAGE_SUBVOLUME:
959
960 /* Note that we set the flag only on the top-level
961 * subvolume of the image. */
962
963 r = btrfs_subvol_set_read_only(i->path, b);
964 if (r < 0)
965 return r;
966
967 break;
968
969 case IMAGE_DIRECTORY:
970 /* For simple directory trees we cannot use the access
971 mode of the top-level directory, since it has an
972 effect on the container itself. However, we can
973 use the "immutable" flag, to at least make the
974 top-level directory read-only. It's not as good as
975 a read-only subvolume, but at least something, and
976 we can read the value back. */
977
978 r = chattr_path(i->path, b ? FS_IMMUTABLE_FL : 0, FS_IMMUTABLE_FL, NULL);
979 if (r < 0)
980 return r;
981
982 break;
983
984 case IMAGE_RAW: {
985 struct stat st;
986
987 if (stat(i->path, &st) < 0)
988 return -errno;
989
990 if (chmod(i->path, (st.st_mode & 0444) | (b ? 0000 : 0200)) < 0)
991 return -errno;
992
993 /* If the images is now read-only, it's a good time to
994 * defrag it, given that no write patterns will
995 * fragment it again. */
996 if (b)
997 (void) btrfs_defrag(i->path);
998 break;
999 }
1000
1001 case IMAGE_BLOCK: {
1002 _cleanup_close_ int fd = -EBADF;
1003 struct stat st;
1004 int state = b;
1005
1006 fd = open(i->path, O_CLOEXEC|O_RDONLY|O_NONBLOCK|O_NOCTTY);
1007 if (fd < 0)
1008 return -errno;
1009
1010 if (fstat(fd, &st) < 0)
1011 return -errno;
1012 if (!S_ISBLK(st.st_mode))
1013 return -ENOTTY;
1014
1015 if (ioctl(fd, BLKROSET, &state) < 0)
1016 return -errno;
1017
1018 break;
1019 }
1020
1021 default:
1022 return -EOPNOTSUPP;
1023 }
1024
1025 return 0;
1026 }
1027
1028 int image_path_lock(const char *path, int operation, LockFile *global, LockFile *local) {
1029 _cleanup_free_ char *p = NULL;
1030 LockFile t = LOCK_FILE_INIT;
1031 struct stat st;
1032 bool exclusive;
1033 int r;
1034
1035 assert(path);
1036 assert(global);
1037 assert(local);
1038
1039 /* Locks an image path. This actually creates two locks: one "local" one, next to the image path
1040 * itself, which might be shared via NFS. And another "global" one, in /run, that uses the
1041 * device/inode number. This has the benefit that we can even lock a tree that is a mount point,
1042 * correctly. */
1043
1044 if (!path_is_absolute(path))
1045 return -EINVAL;
1046
1047 switch (operation & (LOCK_SH|LOCK_EX)) {
1048 case LOCK_SH:
1049 exclusive = false;
1050 break;
1051 case LOCK_EX:
1052 exclusive = true;
1053 break;
1054 default:
1055 return -EINVAL;
1056 }
1057
1058 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1059 *local = *global = (LockFile) LOCK_FILE_INIT;
1060 return 0;
1061 }
1062
1063 /* Prohibit taking exclusive locks on the host image. We can't allow this, since we ourselves are
1064 * running off it after all, and we don't want any images to manipulate the host image. We make an
1065 * exception for shared locks however: we allow those (and make them NOPs since there's no point in
1066 * taking them if there can't be exclusive locks). Strictly speaking these are questionable as well,
1067 * since it means changes made to the host might propagate to the container as they happen (and a
1068 * shared lock kinda suggests that no changes happen at all while it is in place), but it's too
1069 * useful not to allow read-only containers off the host root, hence let's support this, and trust
1070 * the user to do the right thing with this. */
1071 if (path_equal(path, "/")) {
1072 if (exclusive)
1073 return -EBUSY;
1074
1075 *local = *global = (LockFile) LOCK_FILE_INIT;
1076 return 0;
1077 }
1078
1079 if (stat(path, &st) >= 0) {
1080 if (S_ISBLK(st.st_mode))
1081 r = asprintf(&p, "/run/systemd/nspawn/locks/block-%u:%u", major(st.st_rdev), minor(st.st_rdev));
1082 else if (S_ISDIR(st.st_mode) || S_ISREG(st.st_mode))
1083 r = asprintf(&p, "/run/systemd/nspawn/locks/inode-%lu:%lu", (unsigned long) st.st_dev, (unsigned long) st.st_ino);
1084 else
1085 return -ENOTTY;
1086 if (r < 0)
1087 return -ENOMEM;
1088 }
1089
1090 /* For block devices we don't need the "local" lock, as the major/minor lock above should be
1091 * sufficient, since block devices are host local anyway. */
1092 if (!path_startswith(path, "/dev/")) {
1093 r = make_lock_file_for(path, operation, &t);
1094 if (r < 0) {
1095 if (!exclusive && r == -EROFS)
1096 log_debug_errno(r, "Failed to create shared lock for '%s', ignoring: %m", path);
1097 else
1098 return r;
1099 }
1100 }
1101
1102 if (p) {
1103 (void) mkdir_p("/run/systemd/nspawn/locks", 0700);
1104
1105 r = make_lock_file(p, operation, global);
1106 if (r < 0) {
1107 release_lock_file(&t);
1108 return r;
1109 }
1110 } else
1111 *global = (LockFile) LOCK_FILE_INIT;
1112
1113 *local = t;
1114 return 0;
1115 }
1116
1117 int image_set_limit(Image *i, uint64_t referenced_max) {
1118 assert(i);
1119
1120 if (IMAGE_IS_VENDOR(i) || IMAGE_IS_HOST(i))
1121 return -EROFS;
1122
1123 if (i->type != IMAGE_SUBVOLUME)
1124 return -EOPNOTSUPP;
1125
1126 /* We set the quota both for the subvolume as well as for the
1127 * subtree. The latter is mostly for historical reasons, since
1128 * we didn't use to have a concept of subtree quota, and hence
1129 * only modified the subvolume quota. */
1130
1131 (void) btrfs_qgroup_set_limit(i->path, 0, referenced_max);
1132 (void) btrfs_subvol_auto_qgroup(i->path, 0, true);
1133 return btrfs_subvol_set_subtree_quota_limit(i->path, 0, referenced_max);
1134 }
1135
1136 int image_read_metadata(Image *i, const ImagePolicy *image_policy) {
1137 _cleanup_(release_lock_file) LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
1138 int r;
1139
1140 assert(i);
1141
1142 r = image_path_lock(i->path, LOCK_SH|LOCK_NB, &global_lock, &local_lock);
1143 if (r < 0)
1144 return r;
1145
1146 switch (i->type) {
1147
1148 case IMAGE_SUBVOLUME:
1149 case IMAGE_DIRECTORY: {
1150 _cleanup_strv_free_ char **machine_info = NULL, **os_release = NULL, **extension_release = NULL;
1151 sd_id128_t machine_id = SD_ID128_NULL;
1152 _cleanup_free_ char *hostname = NULL;
1153 _cleanup_free_ char *path = NULL;
1154
1155 if (i->class == IMAGE_EXTENSION) {
1156 r = extension_has_forbidden_content(i->path);
1157 if (r < 0)
1158 return r;
1159 if (r > 0)
1160 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM),
1161 "Conflicting content found in image %s, refusing.",
1162 i->name);
1163 }
1164
1165 r = chase("/etc/hostname", i->path, CHASE_PREFIX_ROOT|CHASE_TRAIL_SLASH, &path, NULL);
1166 if (r < 0 && r != -ENOENT)
1167 log_debug_errno(r, "Failed to chase /etc/hostname in image %s: %m", i->name);
1168 else if (r >= 0) {
1169 r = read_etc_hostname(path, &hostname);
1170 if (r < 0)
1171 log_debug_errno(errno, "Failed to read /etc/hostname of image %s: %m", i->name);
1172 }
1173
1174 path = mfree(path);
1175
1176 r = id128_get_machine(i->path, &machine_id);
1177 if (r < 0)
1178 log_debug_errno(r, "Failed to read machine ID in image %s, ignoring: %m", i->name);
1179
1180 r = chase("/etc/machine-info", i->path, CHASE_PREFIX_ROOT|CHASE_TRAIL_SLASH, &path, NULL);
1181 if (r < 0 && r != -ENOENT)
1182 log_debug_errno(r, "Failed to chase /etc/machine-info in image %s: %m", i->name);
1183 else if (r >= 0) {
1184 r = load_env_file_pairs(NULL, path, &machine_info);
1185 if (r < 0)
1186 log_debug_errno(r, "Failed to parse machine-info data of %s: %m", i->name);
1187 }
1188
1189 r = load_os_release_pairs(i->path, &os_release);
1190 if (r < 0)
1191 log_debug_errno(r, "Failed to read os-release in image, ignoring: %m");
1192
1193 r = load_extension_release_pairs(i->path, i->name, /* relax_extension_release_check= */ false, &extension_release);
1194 if (r < 0)
1195 log_debug_errno(r, "Failed to read extension-release in image, ignoring: %m");
1196
1197 free_and_replace(i->hostname, hostname);
1198 i->machine_id = machine_id;
1199 strv_free_and_replace(i->machine_info, machine_info);
1200 strv_free_and_replace(i->os_release, os_release);
1201 strv_free_and_replace(i->extension_release, extension_release);
1202
1203 break;
1204 }
1205
1206 case IMAGE_RAW:
1207 case IMAGE_BLOCK: {
1208 _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
1209 _cleanup_(dissected_image_unrefp) DissectedImage *m = NULL;
1210
1211 r = loop_device_make_by_path(i->path, O_RDONLY, /* sector_size= */ UINT32_MAX, LO_FLAGS_PARTSCAN, LOCK_SH, &d);
1212 if (r < 0)
1213 return r;
1214
1215 r = dissect_loop_device(
1216 d,
1217 /* verity= */ NULL,
1218 /* mount_options= */ NULL,
1219 image_policy,
1220 DISSECT_IMAGE_GENERIC_ROOT |
1221 DISSECT_IMAGE_REQUIRE_ROOT |
1222 DISSECT_IMAGE_RELAX_VAR_CHECK |
1223 DISSECT_IMAGE_READ_ONLY |
1224 DISSECT_IMAGE_USR_NO_ROOT |
1225 DISSECT_IMAGE_ADD_PARTITION_DEVICES |
1226 DISSECT_IMAGE_PIN_PARTITION_DEVICES,
1227 &m);
1228 if (r < 0)
1229 return r;
1230
1231 r = dissected_image_acquire_metadata(m,
1232 DISSECT_IMAGE_VALIDATE_OS |
1233 DISSECT_IMAGE_VALIDATE_OS_EXT);
1234 if (r < 0)
1235 return r;
1236
1237 free_and_replace(i->hostname, m->hostname);
1238 i->machine_id = m->machine_id;
1239 strv_free_and_replace(i->machine_info, m->machine_info);
1240 strv_free_and_replace(i->os_release, m->os_release);
1241 strv_free_and_replace(i->extension_release, m->extension_release);
1242
1243 break;
1244 }
1245
1246 default:
1247 return -EOPNOTSUPP;
1248 }
1249
1250 i->metadata_valid = true;
1251
1252 return 0;
1253 }
1254
1255 int image_name_lock(const char *name, int operation, LockFile *ret) {
1256 const char *p;
1257
1258 assert(name);
1259 assert(ret);
1260
1261 /* Locks an image name, regardless of the precise path used. */
1262
1263 if (streq(name, ".host"))
1264 return -EBUSY;
1265
1266 if (!image_name_is_valid(name))
1267 return -EINVAL;
1268
1269 if (getenv_bool("SYSTEMD_NSPAWN_LOCK") == 0) {
1270 *ret = (LockFile) LOCK_FILE_INIT;
1271 return 0;
1272 }
1273
1274 (void) mkdir_p("/run/systemd/nspawn/locks", 0700);
1275
1276 p = strjoina("/run/systemd/nspawn/locks/name-", name);
1277 return make_lock_file(p, operation, ret);
1278 }
1279
1280 bool image_in_search_path(
1281 ImageClass class,
1282 const char *root,
1283 const char *image) {
1284
1285 assert(image);
1286
1287 NULSTR_FOREACH(path, image_search_path[class]) {
1288 const char *p, *q;
1289 size_t k;
1290
1291 if (!empty_or_root(root)) {
1292 q = path_startswith(path, root);
1293 if (!q)
1294 continue;
1295 } else
1296 q = path;
1297
1298 p = path_startswith(q, path);
1299 if (!p)
1300 continue;
1301
1302 /* Make sure there's a filename following */
1303 k = strcspn(p, "/");
1304 if (k == 0)
1305 continue;
1306
1307 p += k;
1308
1309 /* Accept trailing slashes */
1310 if (p[strspn(p, "/")] == 0)
1311 return true;
1312
1313 }
1314
1315 return false;
1316 }
1317
1318 static const char* const image_type_table[_IMAGE_TYPE_MAX] = {
1319 [IMAGE_DIRECTORY] = "directory",
1320 [IMAGE_SUBVOLUME] = "subvolume",
1321 [IMAGE_RAW] = "raw",
1322 [IMAGE_BLOCK] = "block",
1323 };
1324
1325 DEFINE_STRING_TABLE_LOOKUP(image_type, ImageType);
1326
1327 static const char* const image_class_table[_IMAGE_CLASS_MAX] = {
1328 [IMAGE_MACHINE] = "machine",
1329 [IMAGE_PORTABLE] = "portable",
1330 [IMAGE_EXTENSION] = "extension",
1331 };
1332
1333 DEFINE_STRING_TABLE_LOOKUP(image_class, ImageClass);