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