strtoumax: Avoid link error on OSF/1 with DTK cc.
[gnulib.git] / lib / canonicalize.c
1 /* Return the canonical absolute name of a given file.
2    Copyright (C) 1996-2011 Free Software Foundation, Inc.
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 #include <config.h>
18
19 #include "canonicalize.h"
20
21 #include <errno.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26
27 #include "areadlink.h"
28 #include "file-set.h"
29 #include "hash-triple.h"
30 #include "pathmax.h"
31 #include "xalloc.h"
32 #include "xgetcwd.h"
33
34 /* In this file, we cannot handle file names longer than PATH_MAX.
35    On systems with no file name length limit, use a fallback.  */
36 #ifndef PATH_MAX
37 # define PATH_MAX 8192
38 #endif
39
40 #ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
41 # define DOUBLE_SLASH_IS_DISTINCT_ROOT 0
42 #endif
43
44 #if !((HAVE_CANONICALIZE_FILE_NAME && FUNC_REALPATH_WORKS)      \
45       || GNULIB_CANONICALIZE_LGPL)
46 /* Return the canonical absolute name of file NAME.  A canonical name
47    does not contain any `.', `..' components nor any repeated file name
48    separators ('/') or symlinks.  All components must exist.
49    The result is malloc'd.  */
50
51 char *
52 canonicalize_file_name (const char *name)
53 {
54   return canonicalize_filename_mode (name, CAN_EXISTING);
55 }
56 #endif /* !HAVE_CANONICALIZE_FILE_NAME */
57
58 /* Return true if we've already seen the triple, <FILENAME, dev, ino>.
59    If *HT is not initialized, initialize it.  */
60 static bool
61 seen_triple (Hash_table **ht, char const *filename, struct stat const *st)
62 {
63   if (*ht == NULL)
64     {
65       size_t initial_capacity = 7;
66       *ht = hash_initialize (initial_capacity,
67                             NULL,
68                             triple_hash,
69                             triple_compare_ino_str,
70                             triple_free);
71       if (*ht == NULL)
72         xalloc_die ();
73     }
74
75   if (seen_file (*ht, filename, st))
76     return true;
77
78   record_file (*ht, filename, st);
79   return false;
80 }
81
82 /* Return the canonical absolute name of file NAME, while treating
83    missing elements according to CAN_MODE.  A canonical name
84    does not contain any `.', `..' components nor any repeated file name
85    separators ('/') or symlinks.  Whether components must exist
86    or not depends on canonicalize mode.  The result is malloc'd.  */
87
88 char *
89 canonicalize_filename_mode (const char *name, canonicalize_mode_t can_mode)
90 {
91   char *rname, *dest, *extra_buf = NULL;
92   char const *start;
93   char const *end;
94   char const *rname_limit;
95   size_t extra_len = 0;
96   Hash_table *ht = NULL;
97   int saved_errno;
98
99   if (name == NULL)
100     {
101       errno = EINVAL;
102       return NULL;
103     }
104
105   if (name[0] == '\0')
106     {
107       errno = ENOENT;
108       return NULL;
109     }
110
111   if (name[0] != '/')
112     {
113       rname = xgetcwd ();
114       if (!rname)
115         return NULL;
116       dest = strchr (rname, '\0');
117       if (dest - rname < PATH_MAX)
118         {
119           char *p = xrealloc (rname, PATH_MAX);
120           dest = p + (dest - rname);
121           rname = p;
122           rname_limit = rname + PATH_MAX;
123         }
124       else
125         {
126           rname_limit = dest;
127         }
128     }
129   else
130     {
131       rname = xmalloc (PATH_MAX);
132       rname_limit = rname + PATH_MAX;
133       rname[0] = '/';
134       dest = rname + 1;
135       if (DOUBLE_SLASH_IS_DISTINCT_ROOT && name[1] == '/')
136         *dest++ = '/';
137     }
138
139   for (start = name; *start; start = end)
140     {
141       /* Skip sequence of multiple file name separators.  */
142       while (*start == '/')
143         ++start;
144
145       /* Find end of component.  */
146       for (end = start; *end && *end != '/'; ++end)
147         /* Nothing.  */;
148
149       if (end - start == 0)
150         break;
151       else if (end - start == 1 && start[0] == '.')
152         /* nothing */;
153       else if (end - start == 2 && start[0] == '.' && start[1] == '.')
154         {
155           /* Back up to previous component, ignore if at root already.  */
156           if (dest > rname + 1)
157             while ((--dest)[-1] != '/');
158           if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
159               && *dest == '/')
160             dest++;
161         }
162       else
163         {
164           struct stat st;
165
166           if (dest[-1] != '/')
167             *dest++ = '/';
168
169           if (dest + (end - start) >= rname_limit)
170             {
171               ptrdiff_t dest_offset = dest - rname;
172               size_t new_size = rname_limit - rname;
173
174               if (end - start + 1 > PATH_MAX)
175                 new_size += end - start + 1;
176               else
177                 new_size += PATH_MAX;
178               rname = xrealloc (rname, new_size);
179               rname_limit = rname + new_size;
180
181               dest = rname + dest_offset;
182             }
183
184           dest = memcpy (dest, start, end - start);
185           dest += end - start;
186           *dest = '\0';
187
188           if (lstat (rname, &st) != 0)
189             {
190               saved_errno = errno;
191               if (can_mode == CAN_EXISTING)
192                 goto error;
193               if (can_mode == CAN_ALL_BUT_LAST)
194                 {
195                   if (end[strspn (end, "/")] || saved_errno != ENOENT)
196                     goto error;
197                   continue;
198                 }
199               st.st_mode = 0;
200             }
201
202           if (S_ISLNK (st.st_mode))
203             {
204               char *buf;
205               size_t n, len;
206
207               /* Detect loops.  We cannot use the cycle-check module here,
208                  since it's actually possible to encounter the same symlink
209                  more than once in a given traversal.  However, encountering
210                  the same symlink,NAME pair twice does indicate a loop.  */
211               if (seen_triple (&ht, name, &st))
212                 {
213                   if (can_mode == CAN_MISSING)
214                     continue;
215                   saved_errno = ELOOP;
216                   goto error;
217                 }
218
219               buf = areadlink_with_size (rname, st.st_size);
220               if (!buf)
221                 {
222                   if (can_mode == CAN_MISSING && errno != ENOMEM)
223                     continue;
224                   saved_errno = errno;
225                   goto error;
226                 }
227
228               n = strlen (buf);
229               len = strlen (end);
230
231               if (!extra_len)
232                 {
233                   extra_len =
234                     ((n + len + 1) > PATH_MAX) ? (n + len + 1) : PATH_MAX;
235                   extra_buf = xmalloc (extra_len);
236                 }
237               else if ((n + len + 1) > extra_len)
238                 {
239                   extra_len = n + len + 1;
240                   extra_buf = xrealloc (extra_buf, extra_len);
241                 }
242
243               /* Careful here, end may be a pointer into extra_buf... */
244               memmove (&extra_buf[n], end, len + 1);
245               name = end = memcpy (extra_buf, buf, n);
246
247               if (buf[0] == '/')
248                 {
249                   dest = rname + 1;     /* It's an absolute symlink */
250                   if (DOUBLE_SLASH_IS_DISTINCT_ROOT && buf[1] == '/')
251                     *dest++ = '/';
252                 }
253               else
254                 {
255                   /* Back up to previous component, ignore if at root
256                      already: */
257                   if (dest > rname + 1)
258                     while ((--dest)[-1] != '/');
259                   if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
260                       && *dest == '/')
261                     dest++;
262                 }
263
264               free (buf);
265             }
266           else
267             {
268               if (!S_ISDIR (st.st_mode) && *end && (can_mode != CAN_MISSING))
269                 {
270                   saved_errno = ENOTDIR;
271                   goto error;
272                 }
273             }
274         }
275     }
276   if (dest > rname + 1 && dest[-1] == '/')
277     --dest;
278   if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1 && *dest == '/')
279     dest++;
280   *dest = '\0';
281   if (rname_limit != dest + 1)
282     rname = xrealloc (rname, dest - rname + 1);
283
284   free (extra_buf);
285   if (ht)
286     hash_free (ht);
287   return rname;
288
289 error:
290   free (extra_buf);
291   free (rname);
292   if (ht)
293     hash_free (ht);
294   errno = saved_errno;
295   return NULL;
296 }