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