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