Use rpl_ prefix for functions, so as to avoid endless recursions in weird cases.
[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 3 of the License, or
8    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
17
18 #if !_LIBC
19 # include <config.h>
20 # include <unistd.h>
21 # include "dirfd.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 rpl_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       /* Reset fd.  It may have been closed by fdopendir.  */
238       fd = dirfd (dirstream);
239       fd_needs_closing = false;
240 #else
241       dirstream = __opendir (dotlist);
242       if (dirstream == NULL)
243         goto lose;
244       dotlist[dotlen++] = '/';
245 #endif
246       for (;;)
247         {
248           /* Clear errno to distinguish EOF from error if readdir returns
249              NULL.  */
250           __set_errno (0);
251           d = __readdir (dirstream);
252
253           /* When we've iterated through all directory entries without finding
254              one with a matching d_ino, rewind the stream and consider each
255              name again, but this time, using lstat.  This is necessary in a
256              chroot on at least one system (glibc-2.3.6 + linux 2.6.12), where
257              .., ../.., ../../.., etc. all had the same device number, yet the
258              d_ino values for entries in / did not match those obtained
259              via lstat.  */
260           if (d == NULL && errno == 0 && use_d_ino)
261             {
262               use_d_ino = false;
263               rewinddir (dirstream);
264               d = __readdir (dirstream);
265             }
266
267           if (d == NULL)
268             {
269               if (errno == 0)
270                 /* EOF on dirstream, which can mean e.g., that the current
271                    directory has been removed.  */
272                 __set_errno (ENOENT);
273               goto lose;
274             }
275           if (d->d_name[0] == '.' &&
276               (d->d_name[1] == '\0' ||
277                (d->d_name[1] == '.' && d->d_name[2] == '\0')))
278             continue;
279
280           if (use_d_ino)
281             {
282               bool match = (MATCHING_INO (d, thisino) || mount_point);
283               if (! match)
284                 continue;
285             }
286
287           {
288             int entry_status;
289 #ifdef AT_FDCWD
290             entry_status = fstatat (fd, d->d_name, &st, AT_SYMLINK_NOFOLLOW);
291 #else
292             /* Compute size needed for this file name, or for the file
293                name ".." in the same directory, whichever is larger.
294                Room for ".." might be needed the next time through
295                the outer loop.  */
296             size_t name_alloc = _D_ALLOC_NAMLEN (d);
297             size_t filesize = dotlen + MAX (sizeof "..", name_alloc);
298
299             if (filesize < dotlen)
300               goto memory_exhausted;
301
302             if (dotsize < filesize)
303               {
304                 /* My, what a deep directory tree you have, Grandma.  */
305                 size_t newsize = MAX (filesize, dotsize * 2);
306                 size_t i;
307                 if (newsize < dotsize)
308                   goto memory_exhausted;
309                 if (dotlist != dots)
310                   free (dotlist);
311                 dotlist = malloc (newsize);
312                 if (dotlist == NULL)
313                   goto lose;
314                 dotsize = newsize;
315
316                 i = 0;
317                 do
318                   {
319                     dotlist[i++] = '.';
320                     dotlist[i++] = '.';
321                     dotlist[i++] = '/';
322                   }
323                 while (i < dotlen);
324               }
325
326             memcpy (dotlist + dotlen, d->d_name, _D_ALLOC_NAMLEN (d));
327             entry_status = __lstat (dotlist, &st);
328 #endif
329             /* We don't fail here if we cannot stat() a directory entry.
330                This can happen when (network) file systems fail.  If this
331                entry is in fact the one we are looking for we will find
332                out soon as we reach the end of the directory without
333                having found anything.  */
334             if (entry_status == 0 && S_ISDIR (st.st_mode)
335                 && st.st_dev == thisdev && st.st_ino == thisino)
336               break;
337           }
338         }
339
340       dirroom = dirp - dir;
341       namlen = _D_EXACT_NAMLEN (d);
342
343       if (dirroom <= namlen)
344         {
345           if (size != 0)
346             {
347               __set_errno (ERANGE);
348               goto lose;
349             }
350           else
351             {
352               char *tmp;
353               size_t oldsize = allocated;
354
355               allocated += MAX (allocated, namlen);
356               if (allocated < oldsize
357                   || ! (tmp = realloc (dir, allocated)))
358                 goto memory_exhausted;
359
360               /* Move current contents up to the end of the buffer.
361                  This is guaranteed to be non-overlapping.  */
362               dirp = memcpy (tmp + allocated - (oldsize - dirroom),
363                              tmp + dirroom,
364                              oldsize - dirroom);
365               dir = tmp;
366             }
367         }
368       dirp -= namlen;
369       memcpy (dirp, d->d_name, namlen);
370       *--dirp = '/';
371
372       thisdev = dotdev;
373       thisino = dotino;
374     }
375
376   if (dirstream && __closedir (dirstream) != 0)
377     {
378       dirstream = NULL;
379       goto lose;
380     }
381
382   if (dirp == &dir[allocated - 1])
383     *--dirp = '/';
384
385 #ifndef AT_FDCWD
386   if (dotlist != dots)
387     free (dotlist);
388 #endif
389
390   used = dir + allocated - dirp;
391   memmove (dir, dirp, used);
392
393   if (size == 0)
394     /* Ensure that the buffer is only as large as necessary.  */
395     buf = realloc (dir, used);
396
397   if (buf == NULL)
398     /* Either buf was NULL all along, or `realloc' failed but
399        we still have the original string.  */
400     buf = dir;
401
402   return buf;
403
404  memory_exhausted:
405   __set_errno (ENOMEM);
406  lose:
407   {
408     int save = errno;
409     if (dirstream)
410       __closedir (dirstream);
411 #ifdef AT_FDCWD
412     if (fd_needs_closing)
413       close (fd);
414 #else
415     if (dotlist != dots)
416       free (dotlist);
417 #endif
418     if (buf == NULL)
419       free (dir);
420     __set_errno (save);
421   }
422   return NULL;
423 }
424
425 #ifdef weak_alias
426 weak_alias (__getcwd, getcwd)
427 #endif