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