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