canonicalize: avoid uninitialized memory use
[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)
149         {
150           if (name[1] == '/' && name[2] != '/')
151             *dest++ = '/';
152           *dest = '\0';
153         }
154     }
155
156   for (start = name; *start; start = end)
157     {
158       /* Skip sequence of multiple file name separators.  */
159       while (*start == '/')
160         ++start;
161
162       /* Find end of component.  */
163       for (end = start; *end && *end != '/'; ++end)
164         /* Nothing.  */;
165
166       if (end - start == 0)
167         break;
168       else if (end - start == 1 && start[0] == '.')
169         /* nothing */;
170       else if (end - start == 2 && start[0] == '.' && start[1] == '.')
171         {
172           /* Back up to previous component, ignore if at root already.  */
173           if (dest > rname + 1)
174             while ((--dest)[-1] != '/');
175           if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
176               && *dest == '/' && dest[1] != '/')
177             dest++;
178         }
179       else
180         {
181           struct stat st;
182
183           if (dest[-1] != '/')
184             *dest++ = '/';
185
186           if (dest + (end - start) >= rname_limit)
187             {
188               ptrdiff_t dest_offset = dest - rname;
189               size_t new_size = rname_limit - rname;
190
191               if (end - start + 1 > PATH_MAX)
192                 new_size += end - start + 1;
193               else
194                 new_size += PATH_MAX;
195               rname = xrealloc (rname, new_size);
196               rname_limit = rname + new_size;
197
198               dest = rname + dest_offset;
199             }
200
201           dest = memcpy (dest, start, end - start);
202           dest += end - start;
203           *dest = '\0';
204
205           if (logical && (can_mode == CAN_MISSING))
206             {
207               /* Avoid the stat in this case as it's inconsequential.
208                  i.e. we're neither resolving symlinks or testing
209                  component existence.  */
210               st.st_mode = 0;
211             }
212           else if ((logical ? stat (rname, &st) : lstat (rname, &st)) != 0)
213             {
214               saved_errno = errno;
215               if (can_mode == CAN_EXISTING)
216                 goto error;
217               if (can_mode == CAN_ALL_BUT_LAST)
218                 {
219                   if (end[strspn (end, "/")] || saved_errno != ENOENT)
220                     goto error;
221                   continue;
222                 }
223               st.st_mode = 0;
224             }
225
226           if (S_ISLNK (st.st_mode))
227             {
228               char *buf;
229               size_t n, len;
230
231               /* Detect loops.  We cannot use the cycle-check module here,
232                  since it's actually possible to encounter the same symlink
233                  more than once in a given traversal.  However, encountering
234                  the same symlink,NAME pair twice does indicate a loop.  */
235               if (seen_triple (&ht, name, &st))
236                 {
237                   if (can_mode == CAN_MISSING)
238                     continue;
239                   saved_errno = ELOOP;
240                   goto error;
241                 }
242
243               buf = areadlink_with_size (rname, st.st_size);
244               if (!buf)
245                 {
246                   if (can_mode == CAN_MISSING && errno != ENOMEM)
247                     continue;
248                   saved_errno = errno;
249                   goto error;
250                 }
251
252               n = strlen (buf);
253               len = strlen (end);
254
255               if (!extra_len)
256                 {
257                   extra_len =
258                     ((n + len + 1) > PATH_MAX) ? (n + len + 1) : PATH_MAX;
259                   extra_buf = xmalloc (extra_len);
260                 }
261               else if ((n + len + 1) > extra_len)
262                 {
263                   extra_len = n + len + 1;
264                   extra_buf = xrealloc (extra_buf, extra_len);
265                 }
266
267               /* Careful here, end may be a pointer into extra_buf... */
268               memmove (&extra_buf[n], end, len + 1);
269               name = end = memcpy (extra_buf, buf, n);
270
271               if (buf[0] == '/')
272                 {
273                   dest = rname + 1;     /* It's an absolute symlink */
274                   if (DOUBLE_SLASH_IS_DISTINCT_ROOT)
275                     {
276                       if (buf[1] == '/' && buf[2] != '/')
277                         *dest++ = '/';
278                       *dest = '\0';
279                     }
280                 }
281               else
282                 {
283                   /* Back up to previous component, ignore if at root
284                      already: */
285                   if (dest > rname + 1)
286                     while ((--dest)[-1] != '/');
287                   if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
288                       && *dest == '/' && dest[1] != '/')
289                     dest++;
290                 }
291
292               free (buf);
293             }
294           else
295             {
296               if (!S_ISDIR (st.st_mode) && *end && (can_mode != CAN_MISSING))
297                 {
298                   saved_errno = ENOTDIR;
299                   goto error;
300                 }
301             }
302         }
303     }
304   if (dest > rname + 1 && dest[-1] == '/')
305     --dest;
306   if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
307       && *dest == '/' && dest[1] != '/')
308     dest++;
309   *dest = '\0';
310   if (rname_limit != dest + 1)
311     rname = xrealloc (rname, dest - rname + 1);
312
313   free (extra_buf);
314   if (ht)
315     hash_free (ht);
316   return rname;
317
318 error:
319   free (extra_buf);
320   free (rname);
321   if (ht)
322     hash_free (ht);
323   errno = saved_errno;
324   return NULL;
325 }