1 /* much like chdir(2), but safer
3 Copyright (C) 2005 Free Software Foundation, Inc.
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)
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.
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. */
19 /* written by Jim Meyering */
25 #include "chdir-safer.h"
31 #include <sys/types.h>
35 # define O_DIRECTORY 0
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)
46 /* Like chdir, but fail if DIR is a symbolic link to a directory (or
47 similar funny business), or if DIR is neither readable nor
48 writable. This avoids a minor race condition between when a
49 directory is created or statted and when the process chdirs into it.
51 On some systems, a writable yet unreadable directory cannot be
52 opened via open with O_WRONLY. For example, on Linux 2.6, the
53 open syscall fails with EISDIR. */
55 chdir_no_follow (char const *dir)
59 int open_flags = O_DIRECTORY | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK;
60 int fd = open (dir, O_RDONLY | open_flags);
64 fd = open (dir, O_WRONLY | open_flags);
69 /* If open follows symlinks, lstat DIR and fstat FD to ensure that
70 they are the same file; if they are different files, set errno to
71 ELOOP (the same value that open uses for symlinks with
72 O_NOFOLLOW) so the caller can report a failure. */
76 result = lstat (dir, &sb1);
80 result = fstat (fd, &sb2);
81 if (result == 0 && ! SAME_INODE (sb1, sb2))