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