Make pwd and readlink work also when run with an unreadable parent dir
[gnulib.git] / lib / getcwd.c
1 /* Copyright (C) 1991,92,93,94,95,96,97,98,99,2004,2005,2006,2007 Free Software
2    Foundation, Inc.
3    This file is part of the GNU C Library.
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 along
16    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 #if !_LIBC
20 # include <config.h>
21 # include "getcwd.h"
22 #endif
23
24 #include <errno.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <stdbool.h>
28 #include <stddef.h>
29
30 #include <fcntl.h> /* For AT_FDCWD on Solaris 9.  */
31
32 #ifndef __set_errno
33 # define __set_errno(val) (errno = (val))
34 #endif
35
36 #include <dirent.h>
37 #ifndef _D_EXACT_NAMLEN
38 # define _D_EXACT_NAMLEN(d) strlen ((d)->d_name)
39 #endif
40 #ifndef _D_ALLOC_NAMLEN
41 # define _D_ALLOC_NAMLEN(d) (_D_EXACT_NAMLEN (d) + 1)
42 #endif
43
44 #include <unistd.h>
45 #include <stdlib.h>
46 #include <string.h>
47
48 #if _LIBC
49 # ifndef mempcpy
50 #  define mempcpy __mempcpy
51 # endif
52 #endif
53
54 #include <limits.h>
55
56 /* Work around a bug in Solaris 9 and 10: AT_FDCWD is positive.  Its
57    value exceeds INT_MAX, so its use as an int doesn't conform to the
58    C standard, and GCC and Sun C complain in some cases.  */
59 #if 0 < AT_FDCWD && AT_FDCWD == 0xffd19553
60 # undef AT_FDCWD
61 # define AT_FDCWD (-3041965)
62 #endif
63
64 #ifdef ENAMETOOLONG
65 # define is_ENAMETOOLONG(x) ((x) == ENAMETOOLONG)
66 #else
67 # define is_ENAMETOOLONG(x) 0
68 #endif
69
70 #ifndef MAX
71 # define MAX(a, b) ((a) < (b) ? (b) : (a))
72 #endif
73 #ifndef MIN
74 # define MIN(a, b) ((a) < (b) ? (a) : (b))
75 #endif
76
77 #ifndef PATH_MAX
78 # ifdef MAXPATHLEN
79 #  define PATH_MAX MAXPATHLEN
80 # else
81 #  define PATH_MAX 1024
82 # endif
83 #endif
84
85 #if D_INO_IN_DIRENT
86 # define MATCHING_INO(dp, ino) ((dp)->d_ino == (ino))
87 #else
88 # define MATCHING_INO(dp, ino) true
89 #endif
90
91 #if !_LIBC
92 # define __getcwd getcwd
93 # define __lstat lstat
94 # define __closedir closedir
95 # define __opendir opendir
96 # define __readdir readdir
97 #endif
98
99 /* The results of opendir() in this file are not used with dirfd and fchdir,
100    therefore save some unnecessary recursion in fchdir.c.  */
101 #undef opendir
102 #undef closedir
103 \f
104 /* Get the name of the current working directory, and put it in SIZE
105    bytes of BUF.  Returns NULL if the directory couldn't be determined or
106    SIZE was too small.  If successful, returns BUF.  In GNU, if BUF is
107    NULL, an array is allocated with `malloc'; the array is SIZE bytes long,
108    unless SIZE == 0, in which case it is as big as necessary.  */
109
110 char *
111 __getcwd (char *buf, size_t size)
112 {
113   /* Lengths of big file name components and entire file names, and a
114      deep level of file name nesting.  These numbers are not upper
115      bounds; they are merely large values suitable for initial
116      allocations, designed to be large enough for most real-world
117      uses.  */
118   enum
119     {
120       BIG_FILE_NAME_COMPONENT_LENGTH = 255,
121       BIG_FILE_NAME_LENGTH = MIN (4095, PATH_MAX - 1),
122       DEEP_NESTING = 100
123     };
124
125 #ifdef AT_FDCWD
126   int fd = AT_FDCWD;
127   bool fd_needs_closing = false;
128 #else
129   char dots[DEEP_NESTING * sizeof ".." + BIG_FILE_NAME_COMPONENT_LENGTH + 1];
130   char *dotlist = dots;
131   size_t dotsize = sizeof dots;
132   size_t dotlen = 0;
133 #endif
134   DIR *dirstream = NULL;
135   dev_t rootdev, thisdev;
136   ino_t rootino, thisino;
137   char *dir;
138   register char *dirp;
139   struct stat st;
140   size_t allocated = size;
141   size_t used;
142
143 #if HAVE_PARTLY_WORKING_GETCWD
144   /* The system getcwd works, except it sometimes fails when it
145      shouldn't, setting errno to ERANGE, ENAMETOOLONG, or ENOENT.  If
146      AT_FDCWD is not defined, the algorithm below is O(N**2) and this
147      is much slower than the system getcwd (at least on GNU/Linux).
148      So trust the system getcwd's results unless they look
149      suspicious.
150
151      Use the system getcwd even if we have openat support, since the
152      system getcwd works even when a parent is unreadable, while the
153      openat-based approach does not.  */
154
155 # undef getcwd
156   dir = getcwd (buf, size);
157   if (dir || (errno != ERANGE && !is_ENAMETOOLONG (errno) && errno != ENOENT))
158     return dir;
159 #endif
160
161   if (size == 0)
162     {
163       if (buf != NULL)
164         {
165           __set_errno (EINVAL);
166           return NULL;
167         }
168
169       allocated = BIG_FILE_NAME_LENGTH + 1;
170     }
171
172   if (buf == NULL)
173     {
174       dir = malloc (allocated);
175       if (dir == NULL)
176         return NULL;
177     }
178   else
179     dir = buf;
180
181   dirp = dir + allocated;
182   *--dirp = '\0';
183
184   if (__lstat (".", &st) < 0)
185     goto lose;
186   thisdev = st.st_dev;
187   thisino = st.st_ino;
188
189   if (__lstat ("/", &st) < 0)
190     goto lose;
191   rootdev = st.st_dev;
192   rootino = st.st_ino;
193
194   while (!(thisdev == rootdev && thisino == rootino))
195     {
196       struct dirent *d;
197       dev_t dotdev;
198       ino_t dotino;
199       bool mount_point;
200       int parent_status;
201       size_t dirroom;
202       size_t namlen;
203       bool use_d_ino = true;
204
205       /* Look at the parent directory.  */
206 #ifdef AT_FDCWD
207       fd = openat (fd, "..", O_RDONLY);
208       if (fd < 0)
209         goto lose;
210       fd_needs_closing = true;
211       parent_status = fstat (fd, &st);
212 #else
213       dotlist[dotlen++] = '.';
214       dotlist[dotlen++] = '.';
215       dotlist[dotlen] = '\0';
216       parent_status = __lstat (dotlist, &st);
217 #endif
218       if (parent_status != 0)
219         goto lose;
220
221       if (dirstream && __closedir (dirstream) != 0)
222         {
223           dirstream = NULL;
224           goto lose;
225         }
226
227       /* Figure out if this directory is a mount point.  */
228       dotdev = st.st_dev;
229       dotino = st.st_ino;
230       mount_point = dotdev != thisdev;
231
232       /* Search for the last directory.  */
233 #ifdef AT_FDCWD
234       dirstream = fdopendir (fd);
235       if (dirstream == NULL)
236         goto lose;
237       fd_needs_closing = false;
238 #else
239       dirstream = __opendir (dotlist);
240       if (dirstream == NULL)
241         goto lose;
242       dotlist[dotlen++] = '/';
243 #endif
244       for (;;)
245         {
246           /* Clear errno to distinguish EOF from error if readdir returns
247              NULL.  */
248           __set_errno (0);
249           d = __readdir (dirstream);
250
251           /* When we've iterated through all directory entries without finding
252              one with a matching d_ino, rewind the stream and consider each
253              name again, but this time, using lstat.  This is necessary in a
254              chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where
255              .., ../.., ../../.., etc. all had the same device number, yet the
256              d_ino values for entries in / did not match those obtained
257              via lstat.  */
258           if (d == NULL && errno == 0 && use_d_ino)
259             {
260               use_d_ino = false;
261               rewinddir (dirstream);
262               d = __readdir (dirstream);
263             }
264
265           if (d == NULL)
266             {
267               if (errno == 0)
268                 /* EOF on dirstream, which can mean e.g., that the current
269                    directory has been removed.  */
270                 __set_errno (ENOENT);
271               goto lose;
272             }
273           if (d->d_name[0] == '.' &&
274               (d->d_name[1] == '\0' ||
275                (d->d_name[1] == '.' && d->d_name[2] == '\0')))
276             continue;
277
278           if (use_d_ino)
279             {
280               bool match = (MATCHING_INO (d, thisino) || mount_point);
281               if (! match)
282                 continue;
283             }
284
285           {
286             int entry_status;
287 #ifdef AT_FDCWD
288             entry_status = fstatat (fd, d->d_name, &st, AT_SYMLINK_NOFOLLOW);
289 #else
290             /* Compute size needed for this file name, or for the file
291                name ".." in the same directory, whichever is larger.
292                Room for ".." might be needed the next time through
293                the outer loop.  */
294             size_t name_alloc = _D_ALLOC_NAMLEN (d);
295             size_t filesize = dotlen + MAX (sizeof "..", name_alloc);
296
297             if (filesize < dotlen)
298               goto memory_exhausted;
299
300             if (dotsize < filesize)
301               {
302                 /* My, what a deep directory tree you have, Grandma.  */
303                 size_t newsize = MAX (filesize, dotsize * 2);
304                 size_t i;
305                 if (newsize < dotsize)
306                   goto memory_exhausted;
307                 if (dotlist != dots)
308                   free (dotlist);
309                 dotlist = malloc (newsize);
310                 if (dotlist == NULL)
311                   goto lose;
312                 dotsize = newsize;
313
314                 i = 0;
315                 do
316                   {
317                     dotlist[i++] = '.';
318                     dotlist[i++] = '.';
319                     dotlist[i++] = '/';
320                   }
321                 while (i < dotlen);
322               }
323
324             memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d));
325             entry_status = __lstat (dotlist, &st);
326 #endif
327             /* We don't fail here if we cannot stat() a directory entry.
328                This can happen when (network) file systems fail.  If this
329                entry is in fact the one we are looking for we will find
330                out soon as we reach the end of the directory without
331                having found anything.  */
332             if (entry_status == 0 && S_ISDIR (st.st_mode)
333                 && st.st_dev == thisdev && st.st_ino == thisino)
334               break;
335           }
336         }
337
338       dirroom = dirp - dir;
339       namlen = _D_EXACT_NAMLEN (d);
340
341       if (dirroom <= namlen)
342         {
343           if (size != 0)
344             {
345               __set_errno (ERANGE);
346               goto lose;
347             }
348           else
349             {
350               char *tmp;
351               size_t oldsize = allocated;
352
353               allocated += MAX (allocated, namlen);
354               if (allocated < oldsize
355                   || ! (tmp = realloc (dir, allocated)))
356                 goto memory_exhausted;
357
358               /* Move current contents up to the end of the buffer.
359                  This is guaranteed to be non-overlapping.  */
360               dirp = memcpy (tmp + allocated - (oldsize - dirroom),
361                              tmp + dirroom,
362                              oldsize - dirroom);
363               dir = tmp;
364             }
365         }
366       dirp -= namlen;
367       memcpy (dirp, d->d_name, namlen);
368       *--dirp = '/';
369
370       thisdev = dotdev;
371       thisino = dotino;
372     }
373
374   if (dirstream && __closedir (dirstream) != 0)
375     {
376       dirstream = NULL;
377       goto lose;
378     }
379
380   if (dirp == &dir[allocated - 1])
381     *--dirp = '/';
382
383 #ifndef AT_FDCWD
384   if (dotlist != dots)
385     free (dotlist);
386 #endif
387
388   used = dir + allocated - dirp;
389   memmove (dir, dirp, used);
390
391   if (buf == NULL && size == 0)
392     /* Ensure that the buffer is only as large as necessary.  */
393     buf = realloc (dir, used);
394
395   if (buf == NULL)
396     /* Either buf was NULL all along, or `realloc' failed but
397        we still have the original string.  */
398     buf = dir;
399
400   return buf;
401
402  memory_exhausted:
403   __set_errno (ENOMEM);
404  lose:
405   {
406     int save = errno;
407     if (dirstream)
408       __closedir (dirstream);
409 #ifdef AT_FDCWD
410     if (fd_needs_closing)
411       close (fd);
412 #else
413     if (dotlist != dots)
414       free (dotlist);
415 #endif
416     if (buf == NULL)
417       free (dir);
418     __set_errno (save);
419   }
420   return NULL;
421 }
422
423 #ifdef weak_alias
424 weak_alias (__getcwd, getcwd)
425 #endif