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