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