summaryrefslogtreecommitdiff
path: root/lib/lchmod.c
blob: cc260ce4dc4177f87f8c675f447fc378224488f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/* Implement lchmod on platforms where it does not work correctly.

   Copyright 2020 Free Software Foundation, Inc.

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */

/* written by Paul Eggert */

#include <config.h>

#include <sys/stat.h>

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

#include <intprops.h>

/* Work like lchmod, except when FILE is a symbolic link.
   In that case, set errno to EOPNOTSUPP and return -1.  */

int
lchmod (char const *file, mode_t mode)
{
#if HAVE_FCHMODAT
  return fchmodat (AT_FDCWD, file, mode, AT_SYMLINK_NOFOLLOW);
#elif defined O_PATH && defined AT_FDCWD
  int fd = openat (AT_FDCWD, file, O_PATH | O_NOFOLLOW | O_CLOEXEC);
  if (fd < 0)
    return fd;
  static char const fmt[] = "/proc/self/fd/%d";
  char buf[sizeof fmt - sizeof "%d" + INT_BUFSIZE_BOUND (int)];
  sprintf (buf, fmt, fd);
  int chmod_result = chmod (buf, mode);
  int chmod_errno = errno;
  close (fd);
  if (chmod_result == 0)
    return chmod_result;
  if (chmod_errno != ENOENT)
    {
      errno = chmod_errno;
      return chmod_result;
    }
  /* /proc is not mounted; fall back on racy implementation.  */
#endif

#if HAVE_LSTAT
  struct stat st;
  int lstat_result = lstat (file, &st);
  if (lstat_result != 0)
    return lstat_result;
  if (S_ISLNK (st.st_mode))
    {
      errno = EOPNOTSUPP;
      return -1;
    }
#endif

  return chmod (file, mode);
}