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