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