Debian Codegraph @

src/basic/btrfs-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/btrfs.h>
4 #include <sys/ioctl.h>
5 #include <sys/stat.h>
6
7 #include "alloc-util.h"
8 #include "btrfs-util.h"
9 #include "errno-util.h"
10 #include "fd-util.h"
11 #include "fs-util.h"
12 #include "path-util.h"
13 #include "string-util.h"
14
15 int btrfs_validate_subvolume_name(const char *name) {
16
17 if (!filename_is_valid(name))
18 return -EINVAL;
19
20 if (strlen(name) > BTRFS_SUBVOL_NAME_MAX)
21 return -E2BIG;
22
23 return 0;
24 }
25
26 static int extract_subvolume_name(const char *path, char **ret) {
27 _cleanup_free_ char *fn = NULL;
28 int r;
29
30 assert(path);
31 assert(ret);
32
33 r = path_extract_filename(path, &fn);
34 if (r < 0)
35 return r;
36
37 r = btrfs_validate_subvolume_name(fn);
38 if (r < 0)
39 return r;
40
41 *ret = TAKE_PTR(fn);
42 return 0;
43 }
44
45 int btrfs_subvol_make(int dir_fd, const char *path) {
46 struct btrfs_ioctl_vol_args args = {};
47 _cleanup_free_ char *subvolume = NULL, *parent = NULL;
48 _cleanup_close_ int fd = -EBADF;
49 int r;
50
51 assert(wildcard_fd_is_valid(dir_fd));
52 assert(!isempty(path));
53
54 r = extract_subvolume_name(path, &subvolume);
55 if (r < 0)
56 return r;
57
58 r = path_extract_directory(path, &parent);
59 if (r < 0 && r != -EDESTADDRREQ) /* Propagate error, unless only a filename was specified, which is OK */
60 return r;
61
62 fd = xopenat(dir_fd, parent ?: ".", O_DIRECTORY|O_RDONLY|O_CLOEXEC);
63 if (fd < 0)
64 return fd;
65
66 strncpy(args.name, subvolume, sizeof(args.name)-1);
67
68 return RET_NERRNO(ioctl(fd, BTRFS_IOC_SUBVOL_CREATE, &args));
69 }
70
71 int btrfs_subvol_make_fallback(int dir_fd, const char *path, mode_t mode) {
72 mode_t old, combined;
73 int r;
74
75 assert(path);
76
77 /* Let's work like mkdir(), i.e. take the specified mode, and mask it with the current umask. */
78 old = umask(~mode);
79 combined = old | ~mode;
80 if (combined != ~mode)
81 umask(combined);
82 r = btrfs_subvol_make(dir_fd, path);
83 umask(old);
84
85 if (r >= 0)
86 return 1; /* subvol worked */
87 if (!ERRNO_IS_NOT_SUPPORTED(r))
88 return r;
89
90 if (mkdirat(dir_fd, path, mode) < 0)
91 return -errno;
92
93 return 0; /* plain directory */
94 }