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