1 /* Return the canonical absolute name of a given file.
2 Copyright (C) 1996-2025 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"
30 #include <scratch_buffer.h>
32 #include "attribute.h"
34 #include "hash-triple.h"
37 /* Suppress bogus GCC -Wmaybe-uninitialized warnings. */
38 #if defined GCC_LINT || defined lint
39 # define IF_LINT(Code) Code
41 # define IF_LINT(Code) /* empty */
44 #ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
45 # define DOUBLE_SLASH_IS_DISTINCT_ROOT false
49 # define SLASHES "/\\"
54 /* Avoid false GCC warning "'end_idx' may be used uninitialized". */
55 #if _GL_GNUC_PREREQ (4, 7)
56 # pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
59 /* Return true if FILE's existence can be shown, false (setting errno)
60 otherwise. Follow symbolic links. */
62 file_accessible (char const *file
)
65 return faccessat (AT_FDCWD
, file
, F_OK
, AT_EACCESS
) == 0;
68 return stat (file
, &st
) == 0 || errno
== EOVERFLOW
;
72 /* True if concatenating END as a suffix to a file name means that the
73 code needs to check that the file name is that of a searchable
74 directory, since the canonicalize_filename_mode_stk code won't
75 check this later anyway when it checks an ordinary file name
76 component within END. END must either be empty, or start with a
79 static bool _GL_ATTRIBUTE_PURE
80 suffix_requires_dir_check (char const *end
)
82 /* If END does not start with a slash, the suffix is OK. */
83 while (ISSLASH (*end
))
85 /* Two or more slashes act like a single slash. */
88 while (ISSLASH (*end
));
92 default: return false; /* An ordinary file name component is OK. */
93 case '\0': return true; /* Trailing "/" is trouble. */
94 case '.': break; /* Possibly "." or "..". */
96 /* Trailing "/.", or "/.." even if not trailing, is trouble. */
97 if (!*end
|| (*end
== '.' && (!end
[1] || ISSLASH (end
[1]))))
104 /* Append this to a file name to test whether it is a searchable directory.
105 On POSIX platforms "/" suffices, but "/./" is sometimes needed on
106 macOS 10.13 <https://bugs.gnu.org/30350>, and should also work on
107 platforms like AIX 7.2 that need at least "/.". */
109 #ifdef LSTAT_FOLLOWS_SLASHED_SYMLINK
110 static char const dir_suffix
[] = "/";
112 static char const dir_suffix
[] = "/./";
115 /* Return true if DIR is a searchable dir, false (setting errno) otherwise.
116 DIREND points to the NUL byte at the end of the DIR string.
117 Store garbage into DIREND[0 .. strlen (dir_suffix)]. */
120 dir_check (char *dir
, char *dirend
)
122 strcpy (dirend
, dir_suffix
);
123 return file_accessible (dir
);
126 #if !((HAVE_CANONICALIZE_FILE_NAME && FUNC_REALPATH_WORKS) \
127 || GNULIB_CANONICALIZE_LGPL)
128 /* Return the canonical absolute name of file NAME. A canonical name
129 does not contain any ".", ".." components nor any repeated file name
130 separators ('/') or symlinks. All components must exist.
131 The result is malloc'd. */
134 canonicalize_file_name (const char *name
)
136 return canonicalize_filename_mode (name
, CAN_EXISTING
);
138 #endif /* !HAVE_CANONICALIZE_FILE_NAME */
141 multiple_bits_set (canonicalize_mode_t i
)
143 return (i
& (i
- 1)) != 0;
146 /* Return true if we've already seen the triple, <FILENAME, dev, ino>.
147 If *HT is not initialized, initialize it. */
149 seen_triple (Hash_table
**ht
, char const *filename
, struct stat
const *st
)
153 idx_t initial_capacity
= 7;
154 *ht
= hash_initialize (initial_capacity
,
157 triple_compare_ino_str
,
163 if (seen_file (*ht
, filename
, st
))
166 record_file (*ht
, filename
, st
);
170 /* Scratch buffers used by canonicalize_filename_mode_stk and managed
174 struct scratch_buffer rname
;
175 struct scratch_buffer extra
;
176 struct scratch_buffer link
;
180 canonicalize_filename_mode_stk (const char *name
, canonicalize_mode_t can_mode
,
181 struct realpath_bufs
*bufs
)
186 Hash_table
*ht
= NULL
;
187 bool logical
= (can_mode
& CAN_NOLINKS
) != 0;
190 canonicalize_mode_t can_exist
= can_mode
& CAN_MODE_MASK
;
191 if (multiple_bits_set (can_exist
))
209 char *rname
= bufs
->rname
.data
;
210 bool end_in_extra_buffer
= false;
213 /* This is always zero for Posix hosts, but can be 2 for MS-Windows
214 and MS-DOS X:/foo/bar file names. */
215 idx_t prefix_len
= FILE_SYSTEM_PREFIX_LEN (name
);
217 if (!IS_ABSOLUTE_FILE_NAME (name
))
219 while (!getcwd (bufs
->rname
.data
, bufs
->rname
.length
))
224 if (scratch_buffer_grow (&bufs
->rname
))
234 rname
= bufs
->rname
.data
;
236 dest
= rawmemchr (rname
, '\0');
238 prefix_len
= FILE_SYSTEM_PREFIX_LEN (rname
);
242 dest
= mempcpy (rname
, name
, prefix_len
);
244 if (DOUBLE_SLASH_IS_DISTINCT_ROOT
)
246 if (prefix_len
== 0 /* implies ISSLASH (name[0]) */
247 && ISSLASH (name
[1]) && !ISSLASH (name
[2]))
250 #if defined _WIN32 && !defined __CYGWIN__
251 /* For UNC file names '\\server\path\to\file', extend the prefix
252 to include the server: '\\server\'. */
255 for (i
= 2; name
[i
] != '\0' && !ISSLASH (name
[i
]); )
257 if (name
[i
] != '\0' /* implies ISSLASH (name[i]) */
258 && i
+ 1 < bufs
->rname
.length
)
261 memcpy (dest
, name
+ 2, i
- 2 + 1);
266 /* Either name = '\\server'; this is an invalid file name.
267 Or name = '\\server\...' and server is more than
268 bufs->rname.length - 4 bytes long. In either
269 case, stop the UNC processing. */
276 start
= name
+ prefix_len
;
279 for ( ; *start
; start
= end
)
281 /* Skip sequence of multiple file name separators. */
282 while (ISSLASH (*start
))
285 /* Find end of component. */
286 for (end
= start
; *end
&& !ISSLASH (*end
); ++end
)
289 /* Length of this file name component; it can be zero if a file
291 idx_t startlen
= end
- start
;
295 else if (startlen
== 1 && start
[0] == '.')
297 else if (startlen
== 2 && start
[0] == '.' && start
[1] == '.')
299 /* Back up to previous component, ignore if at root already. */
300 if (dest
> rname
+ prefix_len
+ 1)
301 for (--dest
; dest
> rname
&& !ISSLASH (dest
[-1]); --dest
)
303 if (DOUBLE_SLASH_IS_DISTINCT_ROOT
304 && dest
== rname
+ 1 && !prefix_len
305 && ISSLASH (*dest
) && !ISSLASH (dest
[1]))
310 if (!ISSLASH (dest
[-1]))
313 while (rname
+ bufs
->rname
.length
- dest
314 < startlen
+ sizeof dir_suffix
)
316 idx_t dest_offset
= dest
- rname
;
317 if (!scratch_buffer_grow_preserve (&bufs
->rname
))
319 rname
= bufs
->rname
.data
;
320 dest
= rname
+ dest_offset
;
323 dest
= mempcpy (dest
, start
, startlen
);
332 buf
= bufs
->link
.data
;
333 idx_t bufsize
= bufs
->link
.length
;
334 n
= readlink (rname
, buf
, bufsize
- 1);
337 if (!scratch_buffer_grow (&bufs
->link
))
343 /* A physical traversal and RNAME is a symbolic link. */
349 /* Enough symlinks have been seen that it is time to
350 worry about being in a symlink cycle.
351 Get the device and inode of the parent directory, as
352 pre-2017 POSIX says this info is not reliable for
355 dest
[- startlen
] = '\0';
356 if (stat (*rname
? rname
: ".", &st
) != 0)
358 dest
[- startlen
] = *start
;
360 /* Detect loops. We cannot use the cycle-check module here,
361 since it's possible to encounter the same parent
362 directory more than once in a given traversal. However,
363 encountering the same (parentdir, START) pair twice does
365 if (seen_triple (&ht
, start
, &st
))
367 if (can_exist
== CAN_MISSING
)
376 char *extra_buf
= bufs
->extra
.data
;
377 idx_t end_idx
IF_LINT (= 0);
378 if (end_in_extra_buffer
)
379 end_idx
= end
- extra_buf
;
380 size_t len
= strlen (end
);
381 if (INT_ADD_OVERFLOW (len
, n
))
383 while (bufs
->extra
.length
<= len
+ n
)
385 if (!scratch_buffer_grow_preserve (&bufs
->extra
))
387 extra_buf
= bufs
->extra
.data
;
389 if (end_in_extra_buffer
)
390 end
= extra_buf
+ end_idx
;
392 /* Careful here, end may be a pointer into extra_buf... */
393 memmove (&extra_buf
[n
], end
, len
+ 1);
394 name
= end
= memcpy (extra_buf
, buf
, n
);
395 end_in_extra_buffer
= true;
397 if (IS_ABSOLUTE_FILE_NAME (buf
))
399 idx_t pfxlen
= FILE_SYSTEM_PREFIX_LEN (buf
);
401 dest
= mempcpy (rname
, buf
, pfxlen
);
402 *dest
++ = '/'; /* It's an absolute symlink */
403 if (DOUBLE_SLASH_IS_DISTINCT_ROOT
)
405 if (ISSLASH (buf
[1]) && !ISSLASH (buf
[2]) && !pfxlen
)
409 /* Install the new prefix to be in effect hereafter. */
414 /* Back up to previous component, ignore if at root
416 if (dest
> rname
+ prefix_len
+ 1)
417 for (--dest
; dest
> rname
&& !ISSLASH (dest
[-1]); --dest
)
419 if (DOUBLE_SLASH_IS_DISTINCT_ROOT
&& dest
== rname
+ 1
420 && ISSLASH (*dest
) && !ISSLASH (dest
[1]) && !prefix_len
)
424 else if (! (can_exist
== CAN_MISSING
425 || (suffix_requires_dir_check (end
)
426 ? dir_check (rname
, dest
)
429 : *end
|| file_accessible (rname
))
430 || (can_exist
== CAN_ALL_BUT_LAST
432 && !end
[strspn (end
, SLASHES
)])))
436 if (dest
> rname
+ prefix_len
+ 1 && ISSLASH (dest
[-1]))
438 if (DOUBLE_SLASH_IS_DISTINCT_ROOT
&& dest
== rname
+ 1 && !prefix_len
439 && ISSLASH (*dest
) && !ISSLASH (dest
[1]))
451 char *result
= malloc (dest
- rname
);
454 return memcpy (result
, rname
, dest
- rname
);
457 /* Return the canonical absolute name of file NAME, while treating
458 missing elements according to CAN_MODE. A canonical name
459 does not contain any ".", ".." components nor any repeated file name
460 separators ('/') or, depending on other CAN_MODE flags, symlinks.
461 Whether components must exist or not depends on canonicalize mode.
462 The result is malloc'd. */
465 canonicalize_filename_mode (const char *name
, canonicalize_mode_t can_mode
)
467 struct realpath_bufs bufs
;
468 scratch_buffer_init (&bufs
.rname
);
469 scratch_buffer_init (&bufs
.extra
);
470 scratch_buffer_init (&bufs
.link
);
471 char *result
= canonicalize_filename_mode_stk (name
, can_mode
, &bufs
);
472 scratch_buffer_free (&bufs
.link
);
473 scratch_buffer_free (&bufs
.extra
);
474 scratch_buffer_free (&bufs
.rname
);