Add cross-compilation results for GNU/Hurd.
[gnulib.git] / lib / chdir-safer.c
blobc0644cf951edb0becd4ceb2d3d7adb42eb183e3c
1 /* much like chdir(2), but safer
3 Copyright (C) 2005-2006, 2008-2017 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 3 of the License, or
8 (at your option) any later version.
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, see <https://www.gnu.org/licenses/>. */
18 /* written by Jim Meyering */
20 #include <config.h>
22 #include "chdir-safer.h"
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"
32 #ifndef HAVE_READLINK
33 # define HAVE_READLINK 0
34 #endif
36 /* Like chdir, but fail if DIR is a symbolic link to a directory (or
37 similar funny business). This avoids a minor race condition
38 between when a directory is created or statted and when the process
39 chdirs into it.
41 On older systems lacking full support for O_SEARCH, this function
42 can also fail if DIR is not readable. */
43 int
44 chdir_no_follow (char const *dir)
46 int result = 0;
47 int saved_errno;
48 int fd = open (dir,
49 O_SEARCH | O_DIRECTORY | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK);
50 if (fd < 0)
51 return -1;
53 /* If open follows symlinks, lstat DIR and fstat FD to ensure that
54 they are the same file; if they are different files, set errno to
55 ELOOP (the same value that open uses for symlinks with
56 O_NOFOLLOW) so the caller can report a failure.
57 Skip this check if HAVE_READLINK == 0, which should be the case
58 on any system that lacks symlink support. */
59 if (HAVE_READLINK && ! HAVE_WORKING_O_NOFOLLOW)
61 struct stat sb1;
62 result = lstat (dir, &sb1);
63 if (result == 0)
65 struct stat sb2;
66 result = fstat (fd, &sb2);
67 if (result == 0 && ! SAME_INODE (sb1, sb2))
69 errno = ELOOP;
70 result = -1;
75 if (result == 0)
76 result = fchdir (fd);
78 saved_errno = errno;
79 close (fd);
80 errno = saved_errno;
81 return result;