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