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