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