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