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