]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/machine-image.c
tree-wide: fix invocations of chattr_path()
[thirdparty/systemd.git] / src / shared / machine-image.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2013 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <dirent.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/file.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 #include <linux/fs.h>
30 #include "alloc-util.h"
31 #include "btrfs-util.h"
32 #include "chattr-util.h"
33 #include "copy.h"
34 #include "dirent-util.h"
35 #include "fd-util.h"
36 #include "fs-util.h"
37 #include "hashmap.h"
38 #include "lockfile-util.h"
39 #include "log.h"
40 #include "macro.h"
41 #include "machine-image.h"
42 #include "mkdir.h"
43 #include "path-util.h"
44 #include "rm-rf.h"
45 #include "string-table.h"
46 #include "string-util.h"
47 #include "strv.h"
48 #include "time-util.h"
49 #include "utf8.h"
50 #include "util.h"
51 #include "xattr-util.h"
52
53 static const char image_search_path[] =
54 "/var/lib/machines\0"
55 "/var/lib/container\0" /* legacy */
56 "/usr/local/lib/machines\0"
57 "/usr/lib/machines\0";
58
59 Image *image_unref(Image *i) {
60 if (!i)
61 return NULL;
62
63 free(i->name);
64 free(i->path);
65 free(i);
66 return NULL;
67 }
68
69 static char **image_settings_path(Image *image) {
70 _cleanup_strv_free_ char **l = NULL;
71 char **ret;
72 const char *fn, *s;
73 unsigned i = 0;
74
75 assert(image);
76
77 l = new0(char*, 4);
78 if (!l)
79 return NULL;
80
81 fn = strjoina(image->name, ".nspawn");
82
83 FOREACH_STRING(s, "/etc/systemd/nspawn/", "/run/systemd/nspawn/") {
84 l[i] = strappend(s, fn);
85 if (!l[i])
86 return NULL;
87
88 i++;
89 }
90
91 l[i] = file_in_same_dir(image->path, fn);
92 if (!l[i])
93 return NULL;
94
95 ret = l;
96 l = NULL;
97
98 return ret;
99 }
100
101 static int image_new(
102 ImageType t,
103 const char *pretty,
104 const char *path,
105 const char *filename,
106 bool read_only,
107 usec_t crtime,
108 usec_t mtime,
109 Image **ret) {
110
111 _cleanup_(image_unrefp) Image *i = NULL;
112
113 assert(t >= 0);
114 assert(t < _IMAGE_TYPE_MAX);
115 assert(pretty);
116 assert(filename);
117 assert(ret);
118
119 i = new0(Image, 1);
120 if (!i)
121 return -ENOMEM;
122
123 i->type = t;
124 i->read_only = read_only;
125 i->crtime = crtime;
126 i->mtime = mtime;
127 i->usage = i->usage_exclusive = (uint64_t) -1;
128 i->limit = i->limit_exclusive = (uint64_t) -1;
129
130 i->name = strdup(pretty);
131 if (!i->name)
132 return -ENOMEM;
133
134 if (path)
135 i->path = strjoin(path, "/", filename, NULL);
136 else
137 i->path = strdup(filename);
138
139 if (!i->path)
140 return -ENOMEM;
141
142 path_kill_slashes(i->path);
143
144 *ret = i;
145 i = NULL;
146
147 return 0;
148 }
149
150 static int image_make(
151 const char *pretty,
152 int dfd,
153 const char *path,
154 const char *filename,
155 Image **ret) {
156
157 struct stat st;
158 bool read_only;
159 int r;
160
161 assert(filename);
162
163 /* We explicitly *do* follow symlinks here, since we want to
164 * allow symlinking trees into /var/lib/machines/, and treat
165 * them normally. */
166
167 if (fstatat(dfd, filename, &st, 0) < 0)
168 return -errno;
169
170 read_only =
171 (path && path_startswith(path, "/usr")) ||
172 (faccessat(dfd, filename, W_OK, AT_EACCESS) < 0 && errno == EROFS);
173
174 if (S_ISDIR(st.st_mode)) {
175 _cleanup_close_ int fd = -1;
176 unsigned file_attr = 0;
177
178 if (!ret)
179 return 1;
180
181 if (!pretty)
182 pretty = filename;
183
184 fd = openat(dfd, filename, O_CLOEXEC|O_NOCTTY|O_DIRECTORY);
185 if (fd < 0)
186 return -errno;
187
188 /* btrfs subvolumes have inode 256 */
189 if (st.st_ino == 256) {
190
191 r = btrfs_is_filesystem(fd);
192 if (r < 0)
193 return r;
194 if (r) {
195 BtrfsSubvolInfo info;
196
197 /* It's a btrfs subvolume */
198
199 r = btrfs_subvol_get_info_fd(fd, 0, &info);
200 if (r < 0)
201 return r;
202
203 r = image_new(IMAGE_SUBVOLUME,
204 pretty,
205 path,
206 filename,
207 info.read_only || read_only,
208 info.otime,
209 0,
210 ret);
211 if (r < 0)
212 return r;
213
214 if (btrfs_quota_scan_ongoing(fd) == 0) {
215 BtrfsQuotaInfo quota;
216
217 r = btrfs_subvol_get_subtree_quota_fd(fd, 0, &quota);
218 if (r >= 0) {
219 (*ret)->usage = quota.referenced;
220 (*ret)->usage_exclusive = quota.exclusive;
221
222 (*ret)->limit = quota.referenced_max;
223 (*ret)->limit_exclusive = quota.exclusive_max;
224 }
225 }
226
227 return 1;
228 }
229 }
230
231 /* If the IMMUTABLE bit is set, we consider the
232 * directory read-only. Since the ioctl is not
233 * supported everywhere we ignore failures. */
234 (void) read_attr_fd(fd, &file_attr);
235
236 /* It's just a normal directory. */
237 r = image_new(IMAGE_DIRECTORY,
238 pretty,
239 path,
240 filename,
241 read_only || (file_attr & FS_IMMUTABLE_FL),
242 0,
243 0,
244 ret);
245 if (r < 0)
246 return r;
247
248 return 1;
249
250 } else if (S_ISREG(st.st_mode) && endswith(filename, ".raw")) {
251 usec_t crtime = 0;
252
253 /* It's a RAW disk image */
254
255 if (!ret)
256 return 1;
257
258 fd_getcrtime_at(dfd, filename, &crtime, 0);
259
260 if (!pretty)
261 pretty = strndupa(filename, strlen(filename) - 4);
262
263 r = image_new(IMAGE_RAW,
264 pretty,
265 path,
266 filename,
267 !(st.st_mode & 0222) || read_only,
268 crtime,
269 timespec_load(&st.st_mtim),
270 ret);
271 if (r < 0)
272 return r;
273
274 (*ret)->usage = (*ret)->usage_exclusive = st.st_blocks * 512;
275 (*ret)->limit = (*ret)->limit_exclusive = st.st_size;
276
277 return 1;
278 }
279
280 return 0;
281 }
282
283 int image_find(const char *name, Image **ret) {
284 const char *path;
285 int r;
286
287 assert(name);
288
289 /* There are no images with invalid names */
290 if (!image_name_is_valid(name))
291 return 0;
292
293 NULSTR_FOREACH(path, image_search_path) {
294 _cleanup_closedir_ DIR *d = NULL;
295
296 d = opendir(path);
297 if (!d) {
298 if (errno == ENOENT)
299 continue;
300
301 return -errno;
302 }
303
304 r = image_make(NULL, dirfd(d), path, name, ret);
305 if (r == 0 || r == -ENOENT) {
306 _cleanup_free_ char *raw = NULL;
307
308 raw = strappend(name, ".raw");
309 if (!raw)
310 return -ENOMEM;
311
312 r = image_make(NULL, dirfd(d), path, raw, ret);
313 if (r == 0 || r == -ENOENT)
314 continue;
315 }
316 if (r < 0)
317 return r;
318
319 return 1;
320 }
321
322 if (streq(name, ".host"))
323 return image_make(".host", AT_FDCWD, NULL, "/", ret);
324
325 return 0;
326 };
327
328 int image_discover(Hashmap *h) {
329 const char *path;
330 int r;
331
332 assert(h);
333
334 NULSTR_FOREACH(path, image_search_path) {
335 _cleanup_closedir_ DIR *d = NULL;
336 struct dirent *de;
337
338 d = opendir(path);
339 if (!d) {
340 if (errno == ENOENT)
341 continue;
342
343 return -errno;
344 }
345
346 FOREACH_DIRENT_ALL(de, d, return -errno) {
347 _cleanup_(image_unrefp) Image *image = NULL;
348
349 if (!image_name_is_valid(de->d_name))
350 continue;
351
352 if (hashmap_contains(h, de->d_name))
353 continue;
354
355 r = image_make(NULL, dirfd(d), path, de->d_name, &image);
356 if (r == 0 || r == -ENOENT)
357 continue;
358 if (r < 0)
359 return r;
360
361 r = hashmap_put(h, image->name, image);
362 if (r < 0)
363 return r;
364
365 image = NULL;
366 }
367 }
368
369 if (!hashmap_contains(h, ".host")) {
370 _cleanup_(image_unrefp) Image *image = NULL;
371
372 r = image_make(".host", AT_FDCWD, NULL, "/", &image);
373 if (r < 0)
374 return r;
375
376 r = hashmap_put(h, image->name, image);
377 if (r < 0)
378 return r;
379
380 image = NULL;
381
382 }
383
384 return 0;
385 }
386
387 void image_hashmap_free(Hashmap *map) {
388 Image *i;
389
390 while ((i = hashmap_steal_first(map)))
391 image_unref(i);
392
393 hashmap_free(map);
394 }
395
396 int image_remove(Image *i) {
397 _cleanup_release_lock_file_ LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
398 _cleanup_strv_free_ char **settings = NULL;
399 char **j;
400 int r;
401
402 assert(i);
403
404 if (IMAGE_IS_VENDOR(i) || IMAGE_IS_HOST(i))
405 return -EROFS;
406
407 settings = image_settings_path(i);
408 if (!settings)
409 return -ENOMEM;
410
411 /* Make sure we don't interfere with a running nspawn */
412 r = image_path_lock(i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
413 if (r < 0)
414 return r;
415
416 switch (i->type) {
417
418 case IMAGE_SUBVOLUME:
419 r = btrfs_subvol_remove(i->path, BTRFS_REMOVE_RECURSIVE|BTRFS_REMOVE_QUOTA);
420 if (r < 0)
421 return r;
422 break;
423
424 case IMAGE_DIRECTORY:
425 /* Allow deletion of read-only directories */
426 (void) chattr_path(i->path, 0, FS_IMMUTABLE_FL);
427 r = rm_rf(i->path, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME);
428 if (r < 0)
429 return r;
430
431 break;
432
433 case IMAGE_RAW:
434 if (unlink(i->path) < 0)
435 return -errno;
436 break;
437
438 default:
439 return -EOPNOTSUPP;
440 }
441
442 STRV_FOREACH(j, settings) {
443 if (unlink(*j) < 0 && errno != ENOENT)
444 log_debug_errno(errno, "Failed to unlink %s, ignoring: %m", *j);
445 }
446
447 return 0;
448 }
449
450 static int rename_settings_file(const char *path, const char *new_name) {
451 _cleanup_free_ char *rs = NULL;
452 const char *fn;
453
454 fn = strjoina(new_name, ".nspawn");
455
456 rs = file_in_same_dir(path, fn);
457 if (!rs)
458 return -ENOMEM;
459
460 return rename_noreplace(AT_FDCWD, path, AT_FDCWD, rs);
461 }
462
463 int image_rename(Image *i, const char *new_name) {
464 _cleanup_release_lock_file_ LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT, name_lock = LOCK_FILE_INIT;
465 _cleanup_free_ char *new_path = NULL, *nn = NULL;
466 _cleanup_strv_free_ char **settings = NULL;
467 unsigned file_attr = 0;
468 char **j;
469 int r;
470
471 assert(i);
472
473 if (!image_name_is_valid(new_name))
474 return -EINVAL;
475
476 if (IMAGE_IS_VENDOR(i) || IMAGE_IS_HOST(i))
477 return -EROFS;
478
479 settings = image_settings_path(i);
480 if (!settings)
481 return -ENOMEM;
482
483 /* Make sure we don't interfere with a running nspawn */
484 r = image_path_lock(i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
485 if (r < 0)
486 return r;
487
488 /* Make sure nobody takes the new name, between the time we
489 * checked it is currently unused in all search paths, and the
490 * time we take possesion of it */
491 r = image_name_lock(new_name, LOCK_EX|LOCK_NB, &name_lock);
492 if (r < 0)
493 return r;
494
495 r = image_find(new_name, NULL);
496 if (r < 0)
497 return r;
498 if (r > 0)
499 return -EEXIST;
500
501 switch (i->type) {
502
503 case IMAGE_DIRECTORY:
504 /* Turn of the immutable bit while we rename the image, so that we can rename it */
505 (void) read_attr_path(i->path, &file_attr);
506
507 if (file_attr & FS_IMMUTABLE_FL)
508 (void) chattr_path(i->path, 0, FS_IMMUTABLE_FL);
509
510 /* fall through */
511
512 case IMAGE_SUBVOLUME:
513 new_path = file_in_same_dir(i->path, new_name);
514 break;
515
516 case IMAGE_RAW: {
517 const char *fn;
518
519 fn = strjoina(new_name, ".raw");
520 new_path = file_in_same_dir(i->path, fn);
521 break;
522 }
523
524 default:
525 return -EOPNOTSUPP;
526 }
527
528 if (!new_path)
529 return -ENOMEM;
530
531 nn = strdup(new_name);
532 if (!nn)
533 return -ENOMEM;
534
535 r = rename_noreplace(AT_FDCWD, i->path, AT_FDCWD, new_path);
536 if (r < 0)
537 return r;
538
539 /* Restore the immutable bit, if it was set before */
540 if (file_attr & FS_IMMUTABLE_FL)
541 (void) chattr_path(new_path, FS_IMMUTABLE_FL, FS_IMMUTABLE_FL);
542
543 free(i->path);
544 i->path = new_path;
545 new_path = NULL;
546
547 free(i->name);
548 i->name = nn;
549 nn = NULL;
550
551 STRV_FOREACH(j, settings) {
552 r = rename_settings_file(*j, new_name);
553 if (r < 0 && r != -ENOENT)
554 log_debug_errno(r, "Failed to rename settings file %s, ignoring: %m", *j);
555 }
556
557 return 0;
558 }
559
560 static int clone_settings_file(const char *path, const char *new_name) {
561 _cleanup_free_ char *rs = NULL;
562 const char *fn;
563
564 fn = strjoina(new_name, ".nspawn");
565
566 rs = file_in_same_dir(path, fn);
567 if (!rs)
568 return -ENOMEM;
569
570 return copy_file_atomic(path, rs, 0664, false, 0);
571 }
572
573 int image_clone(Image *i, const char *new_name, bool read_only) {
574 _cleanup_release_lock_file_ LockFile name_lock = LOCK_FILE_INIT;
575 _cleanup_strv_free_ char **settings = NULL;
576 const char *new_path;
577 char **j;
578 int r;
579
580 assert(i);
581
582 if (!image_name_is_valid(new_name))
583 return -EINVAL;
584
585 settings = image_settings_path(i);
586 if (!settings)
587 return -ENOMEM;
588
589 /* Make sure nobody takes the new name, between the time we
590 * checked it is currently unused in all search paths, and the
591 * time we take possesion of it */
592 r = image_name_lock(new_name, LOCK_EX|LOCK_NB, &name_lock);
593 if (r < 0)
594 return r;
595
596 r = image_find(new_name, NULL);
597 if (r < 0)
598 return r;
599 if (r > 0)
600 return -EEXIST;
601
602 switch (i->type) {
603
604 case IMAGE_SUBVOLUME:
605 case IMAGE_DIRECTORY:
606 new_path = strjoina("/var/lib/machines/", new_name);
607
608 r = btrfs_subvol_snapshot(i->path, new_path, (read_only ? BTRFS_SNAPSHOT_READ_ONLY : 0) | BTRFS_SNAPSHOT_FALLBACK_COPY | BTRFS_SNAPSHOT_RECURSIVE | BTRFS_SNAPSHOT_QUOTA);
609
610 /* Enable "subtree" quotas for the copy, if we didn't copy any quota from the source. */
611 if (r >= 0)
612 (void) btrfs_subvol_auto_qgroup(new_path, 0, true);
613
614 break;
615
616 case IMAGE_RAW:
617 new_path = strjoina("/var/lib/machines/", new_name, ".raw");
618
619 r = copy_file_atomic(i->path, new_path, read_only ? 0444 : 0644, false, FS_NOCOW_FL);
620 break;
621
622 default:
623 return -EOPNOTSUPP;
624 }
625
626 if (r < 0)
627 return r;
628
629 STRV_FOREACH(j, settings) {
630 r = clone_settings_file(*j, new_name);
631 if (r < 0 && r != -ENOENT)
632 log_debug_errno(r, "Failed to clone settings %s, ignoring: %m", *j);
633 }
634
635 return 0;
636 }
637
638 int image_read_only(Image *i, bool b) {
639 _cleanup_release_lock_file_ LockFile global_lock = LOCK_FILE_INIT, local_lock = LOCK_FILE_INIT;
640 int r;
641 assert(i);
642
643 if (IMAGE_IS_VENDOR(i) || IMAGE_IS_HOST(i))
644 return -EROFS;
645
646 /* Make sure we don't interfere with a running nspawn */
647 r = image_path_lock(i->path, LOCK_EX|LOCK_NB, &global_lock, &local_lock);
648 if (r < 0)
649 return r;
650
651 switch (i->type) {
652
653 case IMAGE_SUBVOLUME:
654
655 /* Note that we set the flag only on the top-level
656 * subvolume of the image. */
657
658 r = btrfs_subvol_set_read_only(i->path, b);
659 if (r < 0)
660 return r;
661
662 break;
663
664 case IMAGE_DIRECTORY:
665 /* For simple directory trees we cannot use the access
666 mode of the top-level directory, since it has an
667 effect on the container itself. However, we can
668 use the "immutable" flag, to at least make the
669 top-level directory read-only. It's not as good as
670 a read-only subvolume, but at least something, and
671 we can read the value back.*/
672
673 r = chattr_path(i->path, b ? FS_IMMUTABLE_FL : 0, FS_IMMUTABLE_FL);
674 if (r < 0)
675 return r;
676
677 break;
678
679 case IMAGE_RAW: {
680 struct stat st;
681
682 if (stat(i->path, &st) < 0)
683 return -errno;
684
685 if (chmod(i->path, (st.st_mode & 0444) | (b ? 0000 : 0200)) < 0)
686 return -errno;
687
688 /* If the images is now read-only, it's a good time to
689 * defrag it, given that no write patterns will
690 * fragment it again. */
691 if (b)
692 (void) btrfs_defrag(i->path);
693 break;
694 }
695
696 default:
697 return -EOPNOTSUPP;
698 }
699
700 return 0;
701 }
702
703 int image_path_lock(const char *path, int operation, LockFile *global, LockFile *local) {
704 _cleanup_free_ char *p = NULL;
705 LockFile t = LOCK_FILE_INIT;
706 struct stat st;
707 int r;
708
709 assert(path);
710 assert(global);
711 assert(local);
712
713 /* Locks an image path. This actually creates two locks: one
714 * "local" one, next to the image path itself, which might be
715 * shared via NFS. And another "global" one, in /run, that
716 * uses the device/inode number. This has the benefit that we
717 * can even lock a tree that is a mount point, correctly. */
718
719 if (path_equal(path, "/"))
720 return -EBUSY;
721
722 if (!path_is_absolute(path))
723 return -EINVAL;
724
725 if (stat(path, &st) >= 0) {
726 if (asprintf(&p, "/run/systemd/nspawn/locks/inode-%lu:%lu", (unsigned long) st.st_dev, (unsigned long) st.st_ino) < 0)
727 return -ENOMEM;
728 }
729
730 r = make_lock_file_for(path, operation, &t);
731 if (r < 0)
732 return r;
733
734 if (p) {
735 mkdir_p("/run/systemd/nspawn/locks", 0700);
736
737 r = make_lock_file(p, operation, global);
738 if (r < 0) {
739 release_lock_file(&t);
740 return r;
741 }
742 }
743
744 *local = t;
745 return 0;
746 }
747
748 int image_set_limit(Image *i, uint64_t referenced_max) {
749 assert(i);
750
751 if (IMAGE_IS_VENDOR(i) || IMAGE_IS_HOST(i))
752 return -EROFS;
753
754 if (i->type != IMAGE_SUBVOLUME)
755 return -EOPNOTSUPP;
756
757 /* We set the quota both for the subvolume as well as for the
758 * subtree. The latter is mostly for historical reasons, since
759 * we didn't use to have a concept of subtree quota, and hence
760 * only modified the subvolume quota. */
761
762 (void) btrfs_qgroup_set_limit(i->path, 0, referenced_max);
763 (void) btrfs_subvol_auto_qgroup(i->path, 0, true);
764 return btrfs_subvol_set_subtree_quota_limit(i->path, 0, referenced_max);
765 }
766
767 int image_name_lock(const char *name, int operation, LockFile *ret) {
768 const char *p;
769
770 assert(name);
771 assert(ret);
772
773 /* Locks an image name, regardless of the precise path used. */
774
775 if (!image_name_is_valid(name))
776 return -EINVAL;
777
778 if (streq(name, ".host"))
779 return -EBUSY;
780
781 mkdir_p("/run/systemd/nspawn/locks", 0700);
782 p = strjoina("/run/systemd/nspawn/locks/name-", name);
783
784 return make_lock_file(p, operation, ret);
785 }
786
787 bool image_name_is_valid(const char *s) {
788 if (!filename_is_valid(s))
789 return false;
790
791 if (string_has_cc(s, NULL))
792 return false;
793
794 if (!utf8_is_valid(s))
795 return false;
796
797 /* Temporary files for atomically creating new files */
798 if (startswith(s, ".#"))
799 return false;
800
801 return true;
802 }
803
804 static const char* const image_type_table[_IMAGE_TYPE_MAX] = {
805 [IMAGE_DIRECTORY] = "directory",
806 [IMAGE_SUBVOLUME] = "subvolume",
807 [IMAGE_RAW] = "raw",
808 };
809
810 DEFINE_STRING_TABLE_LOOKUP(image_type, ImageType);