1 /* much like chdir(2), but safer
3 Copyright (C) 2005, 2006 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>
33 #include "same-inode.h"
36 # define O_DIRECTORY 0
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. */
48 chdir_no_follow (char const *dir)
53 O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK);
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. */
64 result = lstat (dir, &sb1);
68 result = fstat (fd, &sb2);
69 if (result == 0 && ! SAME_INODE (sb1, sb2))