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