bf5d5b89634d90c28cbcc15c948c746f453c9a72
[gnulib.git] / lib / unlinkat.c
1 /* Work around unlinkat bugs on Solaris 9.
2
3    Copyright (C) 2009 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 <http://www.gnu.org/licenses/>.  */
17
18 /* Written by Eric Blake.  */
19
20 #include <config.h>
21
22 #include <unistd.h>
23
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <string.h>
27 #include <sys/stat.h>
28
29 #include "openat.h"
30
31 #undef unlinkat
32
33 /* unlinkat without AT_REMOVEDIR does not honor trailing / on Solaris
34    9.  Solve it in a similar manner to unlink.  */
35
36 int
37 rpl_unlinkat (int fd, char const *name, int flag)
38 {
39   size_t len;
40   int result = 0;
41   /* rmdir behavior has no problems with trailing slash.  */
42   if (flag & AT_REMOVEDIR)
43     return unlinkat (fd, name, flag);
44
45   len = strlen (name);
46   if (len && ISSLASH (name[len - 1]))
47     {
48       /* See the lengthy comment in unlink.c why we disobey the POSIX
49          rule of letting unlink("link-to-dir/") attempt to unlink a
50          directory.  */
51       struct stat st;
52       result = lstatat (fd, name, &st);
53       if (result == 0)
54         {
55           /* Trailing NUL will overwrite the trailing slash.  */
56           char *short_name = malloc (len);
57           if (!short_name)
58             {
59               errno = EPERM;
60               return -1;
61             }
62           memcpy (short_name, name, len);
63           while (len && ISSLASH (short_name[len - 1]))
64             short_name[--len] = '\0';
65           if (len && (lstatat (fd, short_name, &st) || S_ISLNK (st.st_mode)))
66             {
67               free (short_name);
68               errno = EPERM;
69               return -1;
70             }
71           free (short_name);
72         }
73     }
74   if (!result)
75     result = unlinkat (fd, name, flag);
76   return result;
77 }