Improve name: "count-one-bits" is better than "popcount".
[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 #include <config.h>
22
23 #include "chdir-safer.h"
24
25 #include <stdbool.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <unistd.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include "same-inode.h"
32
33 /* Like chdir, but fail if DIR is a symbolic link to a directory (or
34    similar funny business), or if DIR is not readable.  This avoids a
35    minor race condition between when a directory is created or statted
36    and when the process chdirs into it.  */
37 int
38 chdir_no_follow (char const *dir)
39 {
40   int result = 0;
41   int saved_errno;
42   int fd = open (dir,
43                  O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK);
44   if (fd < 0)
45     return -1;
46
47   /* If open follows symlinks, lstat DIR and fstat FD to ensure that
48      they are the same file; if they are different files, set errno to
49      ELOOP (the same value that open uses for symlinks with
50      O_NOFOLLOW) so the caller can report a failure.  */
51   if (! O_NOFOLLOW)
52     {
53       struct stat sb1;
54       result = lstat (dir, &sb1);
55       if (result == 0)
56         {
57           struct stat sb2;
58           result = fstat (fd, &sb2);
59           if (result == 0 && ! SAME_INODE (sb1, sb2))
60             {
61               errno = ELOOP;
62               result = -1;
63             }
64         }
65     }
66
67   if (result == 0)
68     result = fchdir (fd);
69
70   saved_errno = errno;
71   close (fd);
72   errno = saved_errno;
73   return result;
74 }