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