]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/chattr-util.c
grypt-util: drop two emacs modelines
[thirdparty/systemd.git] / src / basic / chattr-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 Copyright 2010 Lennart Poettering
4 ***/
5
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <sys/ioctl.h>
9 #include <sys/stat.h>
10 #include <linux/fs.h>
11
12 #include "chattr-util.h"
13 #include "fd-util.h"
14 #include "macro.h"
15
16 int chattr_fd(int fd, unsigned value, unsigned mask) {
17 unsigned old_attr, new_attr;
18 struct stat st;
19
20 assert(fd >= 0);
21
22 if (fstat(fd, &st) < 0)
23 return -errno;
24
25 /* Explicitly check whether this is a regular file or
26 * directory. If it is anything else (such as a device node or
27 * fifo), then the ioctl will not hit the file systems but
28 * possibly drivers, where the ioctl might have different
29 * effects. Notably, DRM is using the same ioctl() number. */
30
31 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
32 return -ENOTTY;
33
34 if (mask == 0)
35 return 0;
36
37 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
38 return -errno;
39
40 new_attr = (old_attr & ~mask) | (value & mask);
41 if (new_attr == old_attr)
42 return 0;
43
44 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
45 return -errno;
46
47 return 1;
48 }
49
50 int chattr_path(const char *p, unsigned value, unsigned mask) {
51 _cleanup_close_ int fd = -1;
52
53 assert(p);
54
55 if (mask == 0)
56 return 0;
57
58 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
59 if (fd < 0)
60 return -errno;
61
62 return chattr_fd(fd, value, mask);
63 }
64
65 int read_attr_fd(int fd, unsigned *ret) {
66 struct stat st;
67
68 assert(fd >= 0);
69
70 if (fstat(fd, &st) < 0)
71 return -errno;
72
73 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
74 return -ENOTTY;
75
76 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
77 return -errno;
78
79 return 0;
80 }
81
82 int read_attr_path(const char *p, unsigned *ret) {
83 _cleanup_close_ int fd = -1;
84
85 assert(p);
86 assert(ret);
87
88 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
89 if (fd < 0)
90 return -errno;
91
92 return read_attr_fd(fd, ret);
93 }