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