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