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