5c313bcab9eb3829f8f2121e32701a249e3eb74a
[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 #include "same-inode.h"
34
35 #ifndef O_DIRECTORY
36 # define O_DIRECTORY 0
37 #endif
38
39 #ifndef O_NOFOLLOW
40 # define O_NOFOLLOW 0
41 #endif
42
43 /* Like chdir, but fail if DIR is a symbolic link to a directory (or
44    similar funny business), or if DIR is not readable.  This avoids a
45    minor race condition between when a directory is created or statted
46    and when the process chdirs into it.  */
47 int
48 chdir_no_follow (char const *dir)
49 {
50   int result = 0;
51   int saved_errno;
52   int fd = open (dir,
53                  O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK);
54   if (fd < 0)
55     return -1;
56
57   /* If open follows symlinks, lstat DIR and fstat FD to ensure that
58      they are the same file; if they are different files, set errno to
59      ELOOP (the same value that open uses for symlinks with
60      O_NOFOLLOW) so the caller can report a failure.  */
61   if (! O_NOFOLLOW)
62     {
63       struct stat sb1;
64       result = lstat (dir, &sb1);
65       if (result == 0)
66         {
67           struct stat sb2;
68           result = fstat (fd, &sb2);
69           if (result == 0 && ! SAME_INODE (sb1, sb2))
70             {
71               errno = ELOOP;
72               result = -1;
73             }
74         }
75     }
76
77   if (result == 0)
78     result = fchdir (fd);
79
80   saved_errno = errno;
81   close (fd);
82   errno = saved_errno;
83   return result;
84 }