Debian Codegraph @

lib/lchmod.c

raw
1 /* Implement lchmod on platforms where it does not work correctly.
2
3 Copyright 2020-2026 Free Software Foundation, Inc.
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17
18 /* written by Paul Eggert */
19
20 #include <config.h>
21
22 /* Specification. */
23 #include <sys/stat.h>
24
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <unistd.h>
30
31 #include <intprops.h>
32 #include "issymlink.h"
33 #include "issymlinkat.h"
34
35 /* Work like chmod, except when FILE is a symbolic link.
36 In that case, on systems where permissions on symbolic links are unsupported
37 (such as Linux), set errno to EOPNOTSUPP and return -1. */
38
39 int
40 lchmod (char const *file, mode_t mode)
41 {
42 #ifdef O_PATH
43 /* Open a file descriptor with O_NOFOLLOW, to make sure we don't
44 follow symbolic links, if /proc is mounted. O_PATH is used to
45 avoid a failure if the file is not readable.
46 Cf. <https://sourceware.org/PR14578> */
47 int fd = open (file, O_PATH | O_NOFOLLOW | O_CLOEXEC);
48 if (fd < 0)
49 return fd;
50
51 int err;
52 {
53 int ret = issymlinkat (fd, "");
54 if (ret > 0)
55 err = EOPNOTSUPP;
56 else if (ret == 0)
57 {
58 static char const fmt[] = "/proc/self/fd/%d";
59 char buf[sizeof fmt - sizeof "%d" + INT_BUFSIZE_BOUND (int)];
60 sprintf (buf, fmt, fd);
61 err = chmod (buf, mode) == 0 ? 0 : errno == ENOENT ? -1 : errno;
62 }
63 else
64 err = errno == ENOENT ? -1 : errno;
65 }
66
67 close (fd);
68
69 errno = err;
70 if (0 <= err)
71 return err == 0 ? 0 : -1;
72 #endif
73
74 size_t len = strlen (file);
75 if (len && file[len - 1] == '/')
76 {
77 struct stat st;
78 if (lstat (file, &st) < 0)
79 return -1;
80 if (!S_ISDIR (st.st_mode))
81 {
82 errno = ENOTDIR;
83 return -1;
84 }
85 }
86
87 /* O_PATH + /proc is not supported. */
88
89 if (issymlink (file) > 0)
90 {
91 errno = EOPNOTSUPP;
92 return -1;
93 }
94
95 /* Fall back on chmod, despite a possible race. */
96 return chmod (file, mode);
97 }