1 /* provide consistent interface to chown for systems that don't interpret
2 an ID of -1 as meaning `don't change the corresponding ID'.
4 Copyright (C) 1997, 2004-2007, 2009 Free Software Foundation, Inc.
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 /* written by Jim Meyering */
34 /* Simple stub that always fails with ENOSYS, for mingw. */
36 chown (const char *file _UNUSED_PARAMETER_, uid_t uid _UNUSED_PARAMETER_,
37 gid_t gid _UNUSED_PARAMETER_)
43 #else /* HAVE_CHOWN */
45 /* Below we refer to the system's chown(). */
48 /* The results of open() in this file are not used with fchdir,
49 therefore save some unnecessary work in fchdir.c. */
53 /* Provide a more-closely POSIX-conforming version of chown on
54 systems with one or both of the following problems:
55 - chown doesn't treat an ID of -1 as meaning
56 `don't change the corresponding ID'.
57 - chown doesn't dereference symlinks. */
60 rpl_chown (const char *file, uid_t uid, gid_t gid)
62 # if CHOWN_FAILS_TO_HONOR_ID_OF_NEGATIVE_ONE
63 if (gid == (gid_t) -1 || uid == (uid_t) -1)
65 struct stat file_stats;
67 /* Stat file to get id(s) that should remain unchanged. */
68 if (stat (file, &file_stats))
71 if (gid == (gid_t) -1)
72 gid = file_stats.st_gid;
74 if (uid == (uid_t) -1)
75 uid = file_stats.st_uid;
79 # if CHOWN_MODIFIES_SYMLINK
81 /* Handle the case in which the system-supplied chown function
82 does *not* follow symlinks. Instead, it changes permissions
83 on the symlink itself. To work around that, we open the
84 file (but this can fail due to lack of read or write permission) and
85 use fchown on the resulting descriptor. */
86 int open_flags = O_NONBLOCK | O_NOCTTY;
87 int fd = open (file, O_RDONLY | open_flags);
90 && 0 <= (fd = open (file, O_WRONLY | open_flags))))
92 int result = fchown (fd, uid, gid);
93 int saved_errno = errno;
95 /* POSIX says fchown can fail with errno == EINVAL on sockets,
96 so fall back on chown in that case. */
98 bool fchown_socket_failure =
99 (result != 0 && saved_errno == EINVAL
100 && fstat (fd, &sb) == 0 && S_ISFIFO (sb.st_mode));
104 if (! fchown_socket_failure)
110 else if (errno != EACCES)
115 # if CHOWN_TRAILING_SLASH_BUG
117 size_t len = strlen (file);
119 if (len && file[len - 1] == '/' && stat (file, &st))
124 return chown (file, uid, gid);
127 #endif /* HAVE_CHOWN */