Avoid compile failure on systems without ELOOP (like mingw).
[gnulib.git] / lib / chdir-safer.c
1 /* much like chdir(2), but safer
2
3    Copyright (C) 2005-2006, 2008 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 Jim Meyering */
19
20 #include <config.h>
21
22 #include "chdir-safer.h"
23
24 #include <stdbool.h>
25 #include <fcntl.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include "same-inode.h"
31
32 #ifndef ELOOP
33 # define ELOOP 0
34 #endif
35
36 /* Like chdir, but fail if DIR is a symbolic link to a directory (or
37    similar funny business), or if DIR is not readable.  This avoids a
38    minor race condition between when a directory is created or statted
39    and when the process chdirs into it.  */
40 int
41 chdir_no_follow (char const *dir)
42 {
43   int result = 0;
44   int saved_errno;
45   int fd = open (dir,
46                  O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK);
47   if (fd < 0)
48     return -1;
49
50   /* If open follows symlinks, lstat DIR and fstat FD to ensure that
51      they are the same file; if they are different files, set errno to
52      ELOOP (the same value that open uses for symlinks with
53      O_NOFOLLOW) so the caller can report a failure.  */
54   if (! O_NOFOLLOW)
55     {
56       struct stat sb1;
57       result = lstat (dir, &sb1);
58       if (result == 0)
59         {
60           struct stat sb2;
61           result = fstat (fd, &sb2);
62           if (result == 0 && ! SAME_INODE (sb1, sb2))
63             {
64               errno = ELOOP;
65               result = -1;
66             }
67         }
68     }
69
70   if (result == 0)
71     result = fchdir (fd);
72
73   saved_errno = errno;
74   close (fd);
75   errno = saved_errno;
76   return result;
77 }