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