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