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