]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/chattr-util.c
Add SPDX license identifiers to source files under the LGPL
[thirdparty/systemd.git] / src / basic / chattr-util.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
c8b3094d
LP
2/***
3 This file is part of systemd.
4
5 Copyright 2010 Lennart Poettering
6
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
11
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
19***/
20
11c3a366
TA
21#include <errno.h>
22#include <fcntl.h>
c8b3094d
LP
23#include <sys/ioctl.h>
24#include <sys/stat.h>
25#include <linux/fs.h>
26
27#include "chattr-util.h"
28#include "fd-util.h"
11c3a366 29#include "macro.h"
c8b3094d
LP
30
31int chattr_fd(int fd, unsigned value, unsigned mask) {
32 unsigned old_attr, new_attr;
33 struct stat st;
34
35 assert(fd >= 0);
36
37 if (fstat(fd, &st) < 0)
38 return -errno;
39
40 /* Explicitly check whether this is a regular file or
41 * directory. If it is anything else (such as a device node or
42 * fifo), then the ioctl will not hit the file systems but
43 * possibly drivers, where the ioctl might have different
44 * effects. Notably, DRM is using the same ioctl() number. */
45
46 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
47 return -ENOTTY;
48
49 if (mask == 0)
50 return 0;
51
52 if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
53 return -errno;
54
55 new_attr = (old_attr & ~mask) | (value & mask);
56 if (new_attr == old_attr)
57 return 0;
58
59 if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
60 return -errno;
61
62 return 1;
63}
64
65int chattr_path(const char *p, unsigned value, unsigned mask) {
66 _cleanup_close_ int fd = -1;
67
68 assert(p);
69
70 if (mask == 0)
71 return 0;
72
73 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
74 if (fd < 0)
75 return -errno;
76
77 return chattr_fd(fd, value, mask);
78}
79
80int read_attr_fd(int fd, unsigned *ret) {
81 struct stat st;
82
83 assert(fd >= 0);
84
85 if (fstat(fd, &st) < 0)
86 return -errno;
87
88 if (!S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
89 return -ENOTTY;
90
91 if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
92 return -errno;
93
94 return 0;
95}
96
97int read_attr_path(const char *p, unsigned *ret) {
98 _cleanup_close_ int fd = -1;
99
100 assert(p);
101 assert(ret);
102
103 fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
104 if (fd < 0)
105 return -errno;
106
107 return read_attr_fd(fd, ret);
108}