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