1 /* Return the canonical absolute name of a given file.
2 Copyright (C) 1996-2021 Free Software Foundation, Inc.
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.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
19 #include "canonicalize.h"
31 #include <scratch_buffer.h>
33 #include "attribute.h"
35 #include "hash-triple.h"
38 /* Suppress bogus GCC -Wmaybe-uninitialized warnings. */
39 #if defined GCC_LINT || defined lint
40 # define IF_LINT(Code) Code
42 # define IF_LINT(Code) /* empty */
45 #ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
46 # define DOUBLE_SLASH_IS_DISTINCT_ROOT false
50 # define SLASHES "/\\"
55 /* Return true if FILE's existence can be shown, false (setting errno)
56 otherwise. Follow symbolic links. */
58 file_accessible (char const *file
)
61 return faccessat (AT_FDCWD
, file
, F_OK
, AT_EACCESS
) == 0;
64 return stat (file
, &st
) == 0 || errno
== EOVERFLOW
;
68 /* True if concatenating END as a suffix to a file name means that the
69 code needs to check that the file name is that of a searchable
70 directory, since the canonicalize_filename_mode_stk code won't
71 check this later anyway when it checks an ordinary file name
72 component within END. END must either be empty, or start with a
75 static bool _GL_ATTRIBUTE_PURE
76 suffix_requires_dir_check (char const *end
)
78 /* If END does not start with a slash, the suffix is OK. */
79 while (ISSLASH (*end
))
81 /* Two or more slashes act like a single slash. */
84 while (ISSLASH (*end
));
88 default: return false; /* An ordinary file name component is OK. */
89 case '\0': return true; /* Trailing "/" is trouble. */
90 case '.': break; /* Possibly "." or "..". */
92 /* Trailing "/.", or "/.." even if not trailing, is trouble. */
93 if (!*end
|| (*end
== '.' && (!end
[1] || ISSLASH (end
[1]))))
100 /* Append this to a file name to test whether it is a searchable directory.
101 On POSIX platforms "/" suffices, but "/./" is sometimes needed on
102 macOS 10.13 <https://bugs.gnu.org/30350>, and should also work on
103 platforms like AIX 7.2 that need at least "/.". */
105 #ifdef LSTAT_FOLLOWS_SLASHED_SYMLINK
106 static char const dir_suffix
[] = "/";
108 static char const dir_suffix
[] = "/./";
111 /* Return true if DIR is a searchable dir, false (setting errno) otherwise.
112 DIREND points to the NUL byte at the end of the DIR string.
113 Store garbage into DIREND[0 .. strlen (dir_suffix)]. */
116 dir_check (char *dir
, char *dirend
)
118 strcpy (dirend
, dir_suffix
);
119 return file_accessible (dir
);
122 #if !((HAVE_CANONICALIZE_FILE_NAME && FUNC_REALPATH_WORKS) \
123 || GNULIB_CANONICALIZE_LGPL)
124 /* Return the canonical absolute name of file NAME. A canonical name
125 does not contain any ".", ".." components nor any repeated file name
126 separators ('/') or symlinks. All components must exist.
127 The result is malloc'd. */
130 canonicalize_file_name (const char *name
)
132 return canonicalize_filename_mode (name
, CAN_EXISTING
);
134 #endif /* !HAVE_CANONICALIZE_FILE_NAME */
137 multiple_bits_set (canonicalize_mode_t i
)
139 return (i
& (i
- 1)) != 0;
142 /* Return true if we've already seen the triple, <FILENAME, dev, ino>.
143 If *HT is not initialized, initialize it. */
145 seen_triple (Hash_table
**ht
, char const *filename
, struct stat
const *st
)
149 idx_t initial_capacity
= 7;
150 *ht
= hash_initialize (initial_capacity
,
153 triple_compare_ino_str
,
159 if (seen_file (*ht
, filename
, st
))
162 record_file (*ht
, filename
, st
);
167 /* Act like canonicalize_filename_mode (see below), with an additional argument
168 rname_buf that can be used as temporary storage.
170 If GCC_LINT is defined, do not inline this function with GCC 10.1
171 and later, to avoid creating a pointer to the stack that GCC
172 -Wreturn-local-addr incorrectly complains about. See:
173 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93644
174 Although the noinline attribute can hurt performance a bit, no better way
175 to pacify GCC is known; even an explicit #pragma does not pacify GCC.
176 When the GCC bug is fixed this workaround should be limited to the
177 broken GCC versions. */
178 #if _GL_GNUC_PREREQ (10, 1)
179 # if defined GCC_LINT || defined lint
180 __attribute__ ((__noinline__
))
181 # elif __OPTIMIZE__ && !__NO_INLINE__
182 # define GCC_BOGUS_WRETURN_LOCAL_ADDR
186 canonicalize_filename_mode_stk (const char *name
, canonicalize_mode_t can_mode
,
187 struct scratch_buffer
*rname_buf
)
192 Hash_table
*ht
= NULL
;
193 bool logical
= (can_mode
& CAN_NOLINKS
) != 0;
196 canonicalize_mode_t can_exist
= can_mode
& CAN_MODE_MASK
;
197 if (multiple_bits_set (can_exist
))
215 struct scratch_buffer extra_buffer
, link_buffer
;
216 scratch_buffer_init (&extra_buffer
);
217 scratch_buffer_init (&link_buffer
);
218 scratch_buffer_init (rname_buf
);
219 char *rname_on_stack
= rname_buf
->data
;
220 char *rname
= rname_on_stack
;
221 bool end_in_extra_buffer
= false;
224 /* This is always zero for Posix hosts, but can be 2 for MS-Windows
225 and MS-DOS X:/foo/bar file names. */
226 idx_t prefix_len
= FILE_SYSTEM_PREFIX_LEN (name
);
228 if (!IS_ABSOLUTE_FILE_NAME (name
))
230 while (!getcwd (rname
, rname_buf
->length
))
235 if (scratch_buffer_grow (rname_buf
))
245 rname
= rname_buf
->data
;
247 dest
= rawmemchr (rname
, '\0');
249 prefix_len
= FILE_SYSTEM_PREFIX_LEN (rname
);
253 dest
= mempcpy (rname
, name
, prefix_len
);
255 if (DOUBLE_SLASH_IS_DISTINCT_ROOT
)
257 if (prefix_len
== 0 /* implies ISSLASH (name[0]) */
258 && ISSLASH (name
[1]) && !ISSLASH (name
[2]))
261 #if defined _WIN32 && !defined __CYGWIN__
262 /* For UNC file names '\\server\path\to\file', extend the prefix
263 to include the server: '\\server\'. */
266 for (i
= 2; name
[i
] != '\0' && !ISSLASH (name
[i
]); )
268 if (name
[i
] != '\0' /* implies ISSLASH (name[i]) */
269 && i
+ 1 < rname_buf
->length
)
272 memcpy (dest
, name
+ 2, i
- 2 + 1);
277 /* Either name = '\\server'; this is an invalid file name.
278 Or name = '\\server\...' and server is more than
279 rname_buf->length - 4 bytes long. In either
280 case, stop the UNC processing. */
287 start
= name
+ prefix_len
;
290 for ( ; *start
; start
= end
)
292 /* Skip sequence of multiple file name separators. */
293 while (ISSLASH (*start
))
296 /* Find end of component. */
297 for (end
= start
; *end
&& !ISSLASH (*end
); ++end
)
300 /* Length of this file name component; it can be zero if a file
302 idx_t startlen
= end
- start
;
306 else if (startlen
== 1 && start
[0] == '.')
308 else if (startlen
== 2 && start
[0] == '.' && start
[1] == '.')
310 /* Back up to previous component, ignore if at root already. */
311 if (dest
> rname
+ prefix_len
+ 1)
312 for (--dest
; dest
> rname
&& !ISSLASH (dest
[-1]); --dest
)
314 if (DOUBLE_SLASH_IS_DISTINCT_ROOT
315 && dest
== rname
+ 1 && !prefix_len
316 && ISSLASH (*dest
) && !ISSLASH (dest
[1]))
321 if (!ISSLASH (dest
[-1]))
324 while (rname
+ rname_buf
->length
- dest
325 < startlen
+ sizeof dir_suffix
)
327 idx_t dest_offset
= dest
- rname
;
328 if (!scratch_buffer_grow_preserve (rname_buf
))
330 rname
= rname_buf
->data
;
331 dest
= rname
+ dest_offset
;
334 dest
= mempcpy (dest
, start
, startlen
);
343 buf
= link_buffer
.data
;
344 idx_t bufsize
= link_buffer
.length
;
345 n
= readlink (rname
, buf
, bufsize
- 1);
348 if (!scratch_buffer_grow (&link_buffer
))
354 /* A physical traversal and RNAME is a symbolic link. */
360 /* Enough symlinks have been seen that it is time to
361 worry about being in a symlink cycle.
362 Get the device and inode of the parent directory, as
363 pre-2017 POSIX says this info is not reliable for
366 dest
[- startlen
] = '\0';
367 if (stat (*rname
? rname
: ".", &st
) != 0)
369 dest
[- startlen
] = *start
;
371 /* Detect loops. We cannot use the cycle-check module here,
372 since it's possible to encounter the same parent
373 directory more than once in a given traversal. However,
374 encountering the same (parentdir, START) pair twice does
376 if (seen_triple (&ht
, start
, &st
))
378 if (can_exist
== CAN_MISSING
)
387 char *extra_buf
= extra_buffer
.data
;
388 idx_t end_idx
IF_LINT (= 0);
389 if (end_in_extra_buffer
)
390 end_idx
= end
- extra_buf
;
391 size_t len
= strlen (end
);
392 if (INT_ADD_OVERFLOW (len
, n
))
394 while (extra_buffer
.length
<= len
+ n
)
396 if (!scratch_buffer_grow_preserve (&extra_buffer
))
398 extra_buf
= extra_buffer
.data
;
400 if (end_in_extra_buffer
)
401 end
= extra_buf
+ end_idx
;
403 /* Careful here, end may be a pointer into extra_buf... */
404 memmove (&extra_buf
[n
], end
, len
+ 1);
405 name
= end
= memcpy (extra_buf
, buf
, n
);
406 end_in_extra_buffer
= true;
408 if (IS_ABSOLUTE_FILE_NAME (buf
))
410 idx_t pfxlen
= FILE_SYSTEM_PREFIX_LEN (buf
);
412 dest
= mempcpy (rname
, buf
, pfxlen
);
413 *dest
++ = '/'; /* It's an absolute symlink */
414 if (DOUBLE_SLASH_IS_DISTINCT_ROOT
)
416 if (ISSLASH (buf
[1]) && !ISSLASH (buf
[2]) && !pfxlen
)
420 /* Install the new prefix to be in effect hereafter. */
425 /* Back up to previous component, ignore if at root
427 if (dest
> rname
+ prefix_len
+ 1)
428 for (--dest
; dest
> rname
&& !ISSLASH (dest
[-1]); --dest
)
430 if (DOUBLE_SLASH_IS_DISTINCT_ROOT
&& dest
== rname
+ 1
431 && ISSLASH (*dest
) && !ISSLASH (dest
[1]) && !prefix_len
)
435 else if (! (can_exist
== CAN_MISSING
436 || (suffix_requires_dir_check (end
)
437 ? dir_check (rname
, dest
)
440 : *end
|| file_accessible (rname
))
441 || (can_exist
== CAN_ALL_BUT_LAST
443 && !end
[strspn (end
, SLASHES
)])))
447 if (dest
> rname
+ prefix_len
+ 1 && ISSLASH (dest
[-1]))
449 if (DOUBLE_SLASH_IS_DISTINCT_ROOT
&& dest
== rname
+ 1 && !prefix_len
450 && ISSLASH (*dest
) && !ISSLASH (dest
[1]))
457 scratch_buffer_free (&extra_buffer
);
458 scratch_buffer_free (&link_buffer
);
462 scratch_buffer_free (rname_buf
);
467 char *result
= scratch_buffer_dupfree (rname_buf
, dest
- rname
);
473 /* Return the canonical absolute name of file NAME, while treating
474 missing elements according to CAN_MODE. A canonical name
475 does not contain any ".", ".." components nor any repeated file name
476 separators ('/') or, depending on other CAN_MODE flags, symlinks.
477 Whether components must exist or not depends on canonicalize mode.
478 The result is malloc'd. */
481 canonicalize_filename_mode (const char *name
, canonicalize_mode_t can_mode
)
483 #ifdef GCC_BOGUS_WRETURN_LOCAL_ADDR
484 #warning "GCC might issue a bogus -Wreturn-local-addr warning here."
485 #warning "See <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93644>."
487 struct scratch_buffer rname_buffer
;
488 return canonicalize_filename_mode_stk (name
, can_mode
, &rname_buffer
);