Sync from coreutils.
[gnulib.git] / lib / chdir-safer.c
1 /* much like chdir(2), but safer
2
3    Copyright (C) 2005, 2006 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 2, or (at your option)
8    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, write to the Free Software Foundation,
17    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
18
19 /* written by Jim Meyering */
20
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 #include "chdir-safer.h"
26
27 #include <stdbool.h>
28 #include <fcntl.h>
29 #include <errno.h>
30 #include <unistd.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33
34 #ifndef O_DIRECTORY
35 # define O_DIRECTORY 0
36 #endif
37
38 #ifndef O_NOFOLLOW
39 # define O_NOFOLLOW 0
40 #endif
41
42 #define SAME_INODE(Stat_buf_1, Stat_buf_2) \
43   ((Stat_buf_1).st_ino == (Stat_buf_2).st_ino \
44    && (Stat_buf_1).st_dev == (Stat_buf_2).st_dev)
45
46 /* Like chdir, but fail if DIR is a symbolic link to a directory (or
47    similar funny business), or if DIR is not readable.  This avoids a
48    minor race condition between when a directory is created or statted
49    and when the process chdirs into it.  */
50 int
51 chdir_no_follow (char const *dir)
52 {
53   int result = 0;
54   int saved_errno;
55   int fd = open (dir,
56                  O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK);
57   if (fd < 0)
58     return -1;
59
60   /* If open follows symlinks, lstat DIR and fstat FD to ensure that
61      they are the same file; if they are different files, set errno to
62      ELOOP (the same value that open uses for symlinks with
63      O_NOFOLLOW) so the caller can report a failure.  */
64   if (! O_NOFOLLOW)
65     {
66       struct stat sb1;
67       result = lstat (dir, &sb1);
68       if (result == 0)
69         {
70           struct stat sb2;
71           result = fstat (fd, &sb2);
72           if (result == 0 && ! SAME_INODE (sb1, sb2))
73             {
74               errno = ELOOP;
75               result = -1;
76             }
77         }
78     }
79
80   if (result == 0)
81     result = fchdir (fd);
82
83   saved_errno = errno;
84   close (fd);
85   errno = saved_errno;
86   return result;
87 }