Fix last ChangeLog entry.
[gnulib.git] / lib / canonicalize.c
blob88472cc927c3f35f5cd49b16a7859bd661cd957b
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/>. */
17 #include <config.h>
19 #include "canonicalize.h"
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
27 #include <filename.h>
28 #include <idx.h>
29 #include <intprops.h>
30 #include <scratch_buffer.h>
32 #include "attribute.h"
33 #include "file-set.h"
34 #include "hash-triple.h"
35 #include "xalloc.h"
37 /* Suppress bogus GCC -Wmaybe-uninitialized warnings. */
38 #if defined GCC_LINT || defined lint
39 # define IF_LINT(Code) Code
40 #else
41 # define IF_LINT(Code) /* empty */
42 #endif
44 #ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
45 # define DOUBLE_SLASH_IS_DISTINCT_ROOT false
46 #endif
48 #if ISSLASH ('\\')
49 # define SLASHES "/\\"
50 #else
51 # define SLASHES "/"
52 #endif
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"
57 #endif
59 /* Return true if FILE's existence can be shown, false (setting errno)
60 otherwise. Follow symbolic links. */
61 static bool
62 file_accessible (char const *file)
64 # if HAVE_FACCESSAT
65 return faccessat (AT_FDCWD, file, F_OK, AT_EACCESS) == 0;
66 # else
67 struct stat st;
68 return stat (file, &st) == 0 || errno == EOVERFLOW;
69 # endif
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
77 slash. */
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. */
87 end++;
88 while (ISSLASH (*end));
90 switch (*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]))))
98 return true;
101 return false;
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[] = "/";
111 #else
112 static char const dir_suffix[] = "/./";
113 #endif
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)]. */
119 static bool
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. */
133 char *
134 canonicalize_file_name (const char *name)
136 return canonicalize_filename_mode (name, CAN_EXISTING);
138 #endif /* !HAVE_CANONICALIZE_FILE_NAME */
140 static bool
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. */
148 static bool
149 seen_triple (Hash_table **ht, char const *filename, struct stat const *st)
151 if (*ht == NULL)
153 idx_t initial_capacity = 7;
154 *ht = hash_initialize (initial_capacity,
155 NULL,
156 triple_hash,
157 triple_compare_ino_str,
158 triple_free);
159 if (*ht == NULL)
160 xalloc_die ();
163 if (seen_file (*ht, filename, st))
164 return true;
166 record_file (*ht, filename, st);
167 return false;
170 /* Scratch buffers used by canonicalize_filename_mode_stk and managed
171 by __realpath. */
172 struct realpath_bufs
174 struct scratch_buffer rname;
175 struct scratch_buffer extra;
176 struct scratch_buffer link;
179 static char *
180 canonicalize_filename_mode_stk (const char *name, canonicalize_mode_t can_mode,
181 struct realpath_bufs *bufs)
183 char *dest;
184 char const *start;
185 char const *end;
186 Hash_table *ht = NULL;
187 bool logical = (can_mode & CAN_NOLINKS) != 0;
188 int num_links = 0;
190 canonicalize_mode_t can_exist = can_mode & CAN_MODE_MASK;
191 if (multiple_bits_set (can_exist))
193 errno = EINVAL;
194 return NULL;
197 if (name == NULL)
199 errno = EINVAL;
200 return NULL;
203 if (name[0] == '\0')
205 errno = ENOENT;
206 return NULL;
209 char *rname = bufs->rname.data;
210 bool end_in_extra_buffer = false;
211 bool failed = true;
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))
221 switch (errno)
223 case ERANGE:
224 if (scratch_buffer_grow (&bufs->rname))
225 break;
226 FALLTHROUGH;
227 case ENOMEM:
228 xalloc_die ();
230 default:
231 dest = rname;
232 goto error;
234 rname = bufs->rname.data;
236 dest = rawmemchr (rname, '\0');
237 start = name;
238 prefix_len = FILE_SYSTEM_PREFIX_LEN (rname);
240 else
242 dest = mempcpy (rname, name, prefix_len);
243 *dest++ = '/';
244 if (DOUBLE_SLASH_IS_DISTINCT_ROOT)
246 if (prefix_len == 0 /* implies ISSLASH (name[0]) */
247 && ISSLASH (name[1]) && !ISSLASH (name[2]))
249 *dest++ = '/';
250 #if defined _WIN32 && !defined __CYGWIN__
251 /* For UNC file names '\\server\path\to\file', extend the prefix
252 to include the server: '\\server\'. */
254 idx_t i;
255 for (i = 2; name[i] != '\0' && !ISSLASH (name[i]); )
256 i++;
257 if (name[i] != '\0' /* implies ISSLASH (name[i]) */
258 && i + 1 < bufs->rname.length)
260 prefix_len = i;
261 memcpy (dest, name + 2, i - 2 + 1);
262 dest += i - 2 + 1;
264 else
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. */
272 #endif
274 *dest = '\0';
276 start = name + prefix_len;
279 for ( ; *start; start = end)
281 /* Skip sequence of multiple file name separators. */
282 while (ISSLASH (*start))
283 ++start;
285 /* Find end of component. */
286 for (end = start; *end && !ISSLASH (*end); ++end)
287 /* Nothing. */;
289 /* Length of this file name component; it can be zero if a file
290 name ends in '/'. */
291 idx_t startlen = end - start;
293 if (startlen == 0)
294 break;
295 else if (startlen == 1 && start[0] == '.')
296 /* nothing */;
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)
302 continue;
303 if (DOUBLE_SLASH_IS_DISTINCT_ROOT
304 && dest == rname + 1 && !prefix_len
305 && ISSLASH (*dest) && !ISSLASH (dest[1]))
306 dest++;
308 else
310 if (!ISSLASH (dest[-1]))
311 *dest++ = '/';
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))
318 xalloc_die ();
319 rname = bufs->rname.data;
320 dest = rname + dest_offset;
323 dest = mempcpy (dest, start, startlen);
324 *dest = '\0';
326 char *buf;
327 ssize_t n = -1;
328 if (!logical)
330 while (true)
332 buf = bufs->link.data;
333 idx_t bufsize = bufs->link.length;
334 n = readlink (rname, buf, bufsize - 1);
335 if (n < bufsize - 1)
336 break;
337 if (!scratch_buffer_grow (&bufs->link))
338 xalloc_die ();
341 if (0 <= n)
343 /* A physical traversal and RNAME is a symbolic link. */
345 if (num_links < 20)
346 num_links++;
347 else if (*start)
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
353 symlinks. */
354 struct stat st;
355 dest[- startlen] = '\0';
356 if (stat (*rname ? rname : ".", &st) != 0)
357 goto error;
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
364 indicate a loop. */
365 if (seen_triple (&ht, start, &st))
367 if (can_exist == CAN_MISSING)
368 continue;
369 errno = ELOOP;
370 goto error;
374 buf[n] = '\0';
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))
382 xalloc_die ();
383 while (bufs->extra.length <= len + n)
385 if (!scratch_buffer_grow_preserve (&bufs->extra))
386 xalloc_die ();
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)
406 *dest++ = '/';
407 *dest = '\0';
409 /* Install the new prefix to be in effect hereafter. */
410 prefix_len = pfxlen;
412 else
414 /* Back up to previous component, ignore if at root
415 already: */
416 if (dest > rname + prefix_len + 1)
417 for (--dest; dest > rname && !ISSLASH (dest[-1]); --dest)
418 continue;
419 if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
420 && ISSLASH (*dest) && !ISSLASH (dest[1]) && !prefix_len)
421 dest++;
424 else if (! (can_exist == CAN_MISSING
425 || (suffix_requires_dir_check (end)
426 ? dir_check (rname, dest)
427 : !logical
428 ? errno == EINVAL
429 : *end || file_accessible (rname))
430 || (can_exist == CAN_ALL_BUT_LAST
431 && errno == ENOENT
432 && !end[strspn (end, SLASHES)])))
433 goto error;
436 if (dest > rname + prefix_len + 1 && ISSLASH (dest[-1]))
437 --dest;
438 if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1 && !prefix_len
439 && ISSLASH (*dest) && !ISSLASH (dest[1]))
440 dest++;
441 failed = false;
443 error:
444 if (ht)
445 hash_free (ht);
447 if (failed)
448 return NULL;
450 *dest++ = '\0';
451 char *result = malloc (dest - rname);
452 if (!result)
453 xalloc_die ();
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. */
464 char *
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);
475 return result;