canonicalize, canonicalize-lgpl: support MS-Windows file names
[gnulib.git] / lib / canonicalize-lgpl.c
1 /* Return the canonical absolute name of a given file.
2    Copyright (C) 1996-2012 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 #ifndef _LIBC
19 # define _GL_USE_STDLIB_ALLOC 1
20 # include <config.h>
21 #endif
22
23 #if !HAVE_CANONICALIZE_FILE_NAME || !FUNC_REALPATH_WORKS || defined _LIBC
24
25 /* Don't use __attribute__ __nonnull__ in this compilation unit.  Otherwise gcc
26    optimizes away the name == NULL test below.  */
27 #define _GL_ARG_NONNULL(params)
28
29 /* Specification.  */
30 #include <stdlib.h>
31
32 #include <alloca.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <limits.h>
36 #if HAVE_SYS_PARAM_H || defined _LIBC
37 # include <sys/param.h>
38 #endif
39 #include <sys/stat.h>
40 #include <errno.h>
41 #include <stddef.h>
42
43 #ifdef _LIBC
44 # include <shlib-compat.h>
45 #else
46 # define SHLIB_COMPAT(lib, introduced, obsoleted) 0
47 # define versioned_symbol(lib, local, symbol, version) extern int dummy
48 # define compat_symbol(lib, local, symbol, version)
49 # define weak_alias(local, symbol)
50 # define __canonicalize_file_name canonicalize_file_name
51 # define __realpath realpath
52 # include "pathmax.h"
53 # include "malloca.h"
54 # include "dosname.h"
55 # if HAVE_GETCWD
56 #  if IN_RELOCWRAPPER
57     /* When building the relocatable program wrapper, use the system's getcwd
58        function, not the gnulib override, otherwise we would get a link error.
59      */
60 #   undef getcwd
61 #  endif
62 #  ifdef VMS
63     /* We want the directory in Unix syntax, not in VMS syntax.  */
64 #   define __getcwd(buf, max) getcwd (buf, max, 0)
65 #  else
66 #   define __getcwd getcwd
67 #  endif
68 # else
69 #  define __getcwd(buf, max) getwd (buf)
70 # endif
71 # define __readlink readlink
72 # define __set_errno(e) errno = (e)
73 # ifndef MAXSYMLINKS
74 #  ifdef SYMLOOP_MAX
75 #   define MAXSYMLINKS SYMLOOP_MAX
76 #  else
77 #   define MAXSYMLINKS 20
78 #  endif
79 # endif
80 #endif
81
82 #ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
83 # define DOUBLE_SLASH_IS_DISTINCT_ROOT 0
84 #endif
85
86 #if !FUNC_REALPATH_WORKS || defined _LIBC
87 /* Return the canonical absolute name of file NAME.  A canonical name
88    does not contain any ".", ".." components nor any repeated path
89    separators ('/') or symlinks.  All path components must exist.  If
90    RESOLVED is null, the result is malloc'd; otherwise, if the
91    canonical name is PATH_MAX chars or more, returns null with 'errno'
92    set to ENAMETOOLONG; if the name fits in fewer than PATH_MAX chars,
93    returns the name in RESOLVED.  If the name cannot be resolved and
94    RESOLVED is non-NULL, it contains the path of the first component
95    that cannot be resolved.  If the path can be resolved, RESOLVED
96    holds the same value as the value returned.  */
97
98 char *
99 __realpath (const char *name, char *resolved)
100 {
101   char *rpath, *dest, *extra_buf = NULL;
102   const char *start, *end, *rpath_limit;
103   long int path_max;
104   int num_links = 0;
105   size_t prefix_len;
106
107   if (name == NULL)
108     {
109       /* As per Single Unix Specification V2 we must return an error if
110          either parameter is a null pointer.  We extend this to allow
111          the RESOLVED parameter to be NULL in case the we are expected to
112          allocate the room for the return value.  */
113       __set_errno (EINVAL);
114       return NULL;
115     }
116
117   if (name[0] == '\0')
118     {
119       /* As per Single Unix Specification V2 we must return an error if
120          the name argument points to an empty string.  */
121       __set_errno (ENOENT);
122       return NULL;
123     }
124
125 #ifdef PATH_MAX
126   path_max = PATH_MAX;
127 #else
128   path_max = pathconf (name, _PC_PATH_MAX);
129   if (path_max <= 0)
130     path_max = 8192;
131 #endif
132
133   if (resolved == NULL)
134     {
135       rpath = malloc (path_max);
136       if (rpath == NULL)
137         {
138           /* It's easier to set errno to ENOMEM than to rely on the
139              'malloc-posix' gnulib module.  */
140           errno = ENOMEM;
141           return NULL;
142         }
143     }
144   else
145     rpath = resolved;
146   rpath_limit = rpath + path_max;
147
148   /* This is always zero for Posix hosts, but can be 2 for MS-Windows
149      and MS-DOS X:/foo/bar file names.  */
150   prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
151
152   if (!IS_ABSOLUTE_FILE_NAME (name))
153     {
154       if (!__getcwd (rpath, path_max))
155         {
156           rpath[0] = '\0';
157           goto error;
158         }
159       dest = strchr (rpath, '\0');
160     }
161   else
162     {
163       dest = rpath;
164       if (prefix_len)
165         {
166           memcpy (rpath, name, prefix_len);
167           dest += prefix_len;
168         }
169       *dest++ = '/';
170       if (DOUBLE_SLASH_IS_DISTINCT_ROOT)
171         {
172           if (ISSLASH (name[1]) && !ISSLASH (name[2]) && !prefix_len)
173             *dest++ = '/';
174           *dest = '\0';
175         }
176     }
177
178   for (start = end = name + prefix_len; *start; start = end)
179     {
180 #ifdef _LIBC
181       struct stat64 st;
182 #else
183       struct stat st;
184 #endif
185       int n;
186
187       /* Skip sequence of multiple path-separators.  */
188       while (ISSLASH (*start))
189         ++start;
190
191       /* Find end of path component.  */
192       for (end = start; *end && !ISSLASH (*end); ++end)
193         /* Nothing.  */;
194
195       if (end - start == 0)
196         break;
197       else if (end - start == 1 && start[0] == '.')
198         /* nothing */;
199       else if (end - start == 2 && start[0] == '.' && start[1] == '.')
200         {
201           /* Back up to previous component, ignore if at root already.  */
202           if (dest > rpath + prefix_len + 1)
203             for (--dest; !ISSLASH (dest[-1]); --dest)
204               continue;
205           if (DOUBLE_SLASH_IS_DISTINCT_ROOT
206               && dest == rpath + 1 && !prefix_len
207               && ISSLASH (*dest) && !ISSLASH (dest[1]))
208             dest++;
209         }
210       else
211         {
212           size_t new_size;
213
214           if (!ISSLASH (dest[-1]))
215             *dest++ = '/';
216
217           if (dest + (end - start) >= rpath_limit)
218             {
219               ptrdiff_t dest_offset = dest - rpath;
220               char *new_rpath;
221
222               if (resolved)
223                 {
224                   __set_errno (ENAMETOOLONG);
225                   if (dest > rpath + prefix_len + 1)
226                     dest--;
227                   *dest = '\0';
228                   goto error;
229                 }
230               new_size = rpath_limit - rpath;
231               if (end - start + 1 > path_max)
232                 new_size += end - start + 1;
233               else
234                 new_size += path_max;
235               new_rpath = (char *) realloc (rpath, new_size);
236               if (new_rpath == NULL)
237                 {
238                   /* It's easier to set errno to ENOMEM than to rely on the
239                      'realloc-posix' gnulib module.  */
240                   errno = ENOMEM;
241                   goto error;
242                 }
243               rpath = new_rpath;
244               rpath_limit = rpath + new_size;
245
246               dest = rpath + dest_offset;
247             }
248
249 #ifdef _LIBC
250           dest = __mempcpy (dest, start, end - start);
251 #else
252           memcpy (dest, start, end - start);
253           dest += end - start;
254 #endif
255           *dest = '\0';
256
257 #ifdef _LIBC
258           if (__lxstat64 (_STAT_VER, rpath, &st) < 0)
259 #else
260           if (lstat (rpath, &st) < 0)
261 #endif
262             goto error;
263
264           if (S_ISLNK (st.st_mode))
265             {
266               char *buf;
267               size_t len;
268
269               if (++num_links > MAXSYMLINKS)
270                 {
271                   __set_errno (ELOOP);
272                   goto error;
273                 }
274
275               buf = malloca (path_max);
276               if (!buf)
277                 {
278                   errno = ENOMEM;
279                   goto error;
280                 }
281
282               n = __readlink (rpath, buf, path_max - 1);
283               if (n < 0)
284                 {
285                   int saved_errno = errno;
286                   freea (buf);
287                   errno = saved_errno;
288                   goto error;
289                 }
290               buf[n] = '\0';
291
292               if (!extra_buf)
293                 {
294                   extra_buf = malloca (path_max);
295                   if (!extra_buf)
296                     {
297                       freea (buf);
298                       errno = ENOMEM;
299                       goto error;
300                     }
301                 }
302
303               len = strlen (end);
304               if ((long int) (n + len) >= path_max)
305                 {
306                   freea (buf);
307                   __set_errno (ENAMETOOLONG);
308                   goto error;
309                 }
310
311               /* Careful here, end may be a pointer into extra_buf... */
312               memmove (&extra_buf[n], end, len + 1);
313               name = end = memcpy (extra_buf, buf, n);
314
315               if (IS_ABSOLUTE_FILE_NAME (buf))
316                 {
317                   size_t pfxlen = FILE_SYSTEM_PREFIX_LEN (buf);
318
319                   if (pfxlen)
320                     memcpy (rpath, buf, pfxlen);
321                   dest = rpath + pfxlen;
322                   *dest++ = '/'; /* It's an absolute symlink */
323                   if (DOUBLE_SLASH_IS_DISTINCT_ROOT)
324                     {
325                       if (ISSLASH (buf[1]) && !ISSLASH (buf[2]) && !pfxlen)
326                         *dest++ = '/';
327                       *dest = '\0';
328                     }
329                   /* Install the new prefix to be in effect hereafter.  */
330                   prefix_len = pfxlen;
331                 }
332               else
333                 {
334                   /* Back up to previous component, ignore if at root
335                      already: */
336                   if (dest > rpath + prefix_len + 1)
337                     for (--dest; !ISSLASH (dest[-1]); --dest)
338                       continue;
339                   if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rpath + 1
340                       && ISSLASH (*dest) && !ISSLASH (dest[1]) && !prefix_len)
341                     dest++;
342                 }
343             }
344           else if (!S_ISDIR (st.st_mode) && *end != '\0')
345             {
346               __set_errno (ENOTDIR);
347               goto error;
348             }
349         }
350     }
351   if (dest > rpath + prefix_len + 1 && ISSLASH (dest[-1]))
352     --dest;
353   if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rpath + 1 && !prefix_len
354       && ISSLASH (*dest) && !ISSLASH (dest[1]))
355     dest++;
356   *dest = '\0';
357
358   if (extra_buf)
359     freea (extra_buf);
360
361   return rpath;
362
363 error:
364   {
365     int saved_errno = errno;
366     if (extra_buf)
367       freea (extra_buf);
368     if (resolved == NULL)
369       free (rpath);
370     errno = saved_errno;
371   }
372   return NULL;
373 }
374 versioned_symbol (libc, __realpath, realpath, GLIBC_2_3);
375 #endif /* !FUNC_REALPATH_WORKS || defined _LIBC */
376
377
378 #if SHLIB_COMPAT(libc, GLIBC_2_0, GLIBC_2_3)
379 char *
380 attribute_compat_text_section
381 __old_realpath (const char *name, char *resolved)
382 {
383   if (resolved == NULL)
384     {
385       __set_errno (EINVAL);
386       return NULL;
387     }
388
389   return __realpath (name, resolved);
390 }
391 compat_symbol (libc, __old_realpath, realpath, GLIBC_2_0);
392 #endif
393
394
395 char *
396 __canonicalize_file_name (const char *name)
397 {
398   return __realpath (name, NULL);
399 }
400 weak_alias (__canonicalize_file_name, canonicalize_file_name)
401
402 #else
403
404 /* This declaration is solely to ensure that after preprocessing
405    this file is never empty.  */
406 typedef int dummy;
407
408 #endif