e84c3392ed36feac5fa56864440d561c06fea82c
[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 #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, depdending 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 ? stat (rname, &st) : lstat (rname, &st)) != 0)
202             {
203               saved_errno = errno;
204               if (can_mode == CAN_EXISTING)
205                 goto error;
206               if (can_mode == CAN_ALL_BUT_LAST)
207                 {
208                   if (end[strspn (end, "/")] || saved_errno != ENOENT)
209                     goto error;
210                   continue;
211                 }
212               st.st_mode = 0;
213             }
214
215           if (S_ISLNK (st.st_mode))
216             {
217               char *buf;
218               size_t n, len;
219
220               /* Detect loops.  We cannot use the cycle-check module here,
221                  since it's actually possible to encounter the same symlink
222                  more than once in a given traversal.  However, encountering
223                  the same symlink,NAME pair twice does indicate a loop.  */
224               if (seen_triple (&ht, name, &st))
225                 {
226                   if (can_mode == CAN_MISSING)
227                     continue;
228                   saved_errno = ELOOP;
229                   goto error;
230                 }
231
232               buf = areadlink_with_size (rname, st.st_size);
233               if (!buf)
234                 {
235                   if (can_mode == CAN_MISSING && errno != ENOMEM)
236                     continue;
237                   saved_errno = errno;
238                   goto error;
239                 }
240
241               n = strlen (buf);
242               len = strlen (end);
243
244               if (!extra_len)
245                 {
246                   extra_len =
247                     ((n + len + 1) > PATH_MAX) ? (n + len + 1) : PATH_MAX;
248                   extra_buf = xmalloc (extra_len);
249                 }
250               else if ((n + len + 1) > extra_len)
251                 {
252                   extra_len = n + len + 1;
253                   extra_buf = xrealloc (extra_buf, extra_len);
254                 }
255
256               /* Careful here, end may be a pointer into extra_buf... */
257               memmove (&extra_buf[n], end, len + 1);
258               name = end = memcpy (extra_buf, buf, n);
259
260               if (buf[0] == '/')
261                 {
262                   dest = rname + 1;     /* It's an absolute symlink */
263                   if (DOUBLE_SLASH_IS_DISTINCT_ROOT && buf[1] == '/')
264                     *dest++ = '/';
265                 }
266               else
267                 {
268                   /* Back up to previous component, ignore if at root
269                      already: */
270                   if (dest > rname + 1)
271                     while ((--dest)[-1] != '/');
272                   if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
273                       && *dest == '/')
274                     dest++;
275                 }
276
277               free (buf);
278             }
279           else
280             {
281               if (!S_ISDIR (st.st_mode) && *end && (can_mode != CAN_MISSING))
282                 {
283                   saved_errno = ENOTDIR;
284                   goto error;
285                 }
286             }
287         }
288     }
289   if (dest > rname + 1 && dest[-1] == '/')
290     --dest;
291   if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1 && *dest == '/')
292     dest++;
293   *dest = '\0';
294   if (rname_limit != dest + 1)
295     rname = xrealloc (rname, dest - rname + 1);
296
297   free (extra_buf);
298   if (ht)
299     hash_free (ht);
300   return rname;
301
302 error:
303   free (extra_buf);
304   free (rname);
305   if (ht)
306     hash_free (ht);
307   errno = saved_errno;
308   return NULL;
309 }