canonicalize-lgpl.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /* Return the canonical absolute name of a given file.
  2. Copyright (C) 1996-2022 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <https://www.gnu.org/licenses/>. */
  15. #ifndef _LIBC
  16. /* Don't use __attribute__ __nonnull__ in this compilation unit. Otherwise gcc
  17. optimizes away the name == NULL test below. */
  18. # define _GL_ARG_NONNULL(params)
  19. # include <libc-config.h>
  20. #endif
  21. /* Specification. */
  22. #include <stdlib.h>
  23. #include <errno.h>
  24. #include <fcntl.h>
  25. #include <limits.h>
  26. #include <stdbool.h>
  27. #include <string.h>
  28. #include <sys/stat.h>
  29. #include <unistd.h>
  30. #include <eloop-threshold.h>
  31. #include <filename.h>
  32. #include <idx.h>
  33. #include <intprops.h>
  34. #include <scratch_buffer.h>
  35. #ifdef _LIBC
  36. # include <shlib-compat.h>
  37. # define GCC_LINT 1
  38. # define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
  39. #else
  40. # define __canonicalize_file_name canonicalize_file_name
  41. # define __realpath realpath
  42. # include "pathmax.h"
  43. # define __faccessat faccessat
  44. # if defined _WIN32 && !defined __CYGWIN__
  45. # define __getcwd _getcwd
  46. # elif HAVE_GETCWD
  47. # if IN_RELOCWRAPPER
  48. /* When building the relocatable program wrapper, use the system's getcwd
  49. function, not the gnulib override, otherwise we would get a link error.
  50. */
  51. # undef getcwd
  52. # endif
  53. # if defined VMS && !defined getcwd
  54. /* We want the directory in Unix syntax, not in VMS syntax.
  55. The gnulib override of 'getcwd' takes 2 arguments; the original VMS
  56. 'getcwd' takes 3 arguments. */
  57. # define __getcwd(buf, max) getcwd (buf, max, 0)
  58. # else
  59. # define __getcwd getcwd
  60. # endif
  61. # else
  62. # define __getcwd(buf, max) getwd (buf)
  63. # endif
  64. # define __mempcpy mempcpy
  65. # define __pathconf pathconf
  66. # define __rawmemchr rawmemchr
  67. # define __readlink readlink
  68. # if IN_RELOCWRAPPER
  69. /* When building the relocatable program wrapper, use the system's memmove
  70. function, not the gnulib override, otherwise we would get a link error.
  71. */
  72. # undef memmove
  73. # endif
  74. #endif
  75. /* Suppress bogus GCC -Wmaybe-uninitialized warnings. */
  76. #if defined GCC_LINT || defined lint
  77. # define IF_LINT(Code) Code
  78. #else
  79. # define IF_LINT(Code) /* empty */
  80. #endif
  81. #ifndef DOUBLE_SLASH_IS_DISTINCT_ROOT
  82. # define DOUBLE_SLASH_IS_DISTINCT_ROOT false
  83. #endif
  84. #if defined _LIBC || !FUNC_REALPATH_WORKS
  85. /* Return true if FILE's existence can be shown, false (setting errno)
  86. otherwise. Follow symbolic links. */
  87. static bool
  88. file_accessible (char const *file)
  89. {
  90. # if defined _LIBC || HAVE_FACCESSAT
  91. return __faccessat (AT_FDCWD, file, F_OK, AT_EACCESS) == 0;
  92. # else
  93. struct stat st;
  94. return stat (file, &st) == 0 || errno == EOVERFLOW;
  95. # endif
  96. }
  97. /* True if concatenating END as a suffix to a file name means that the
  98. code needs to check that the file name is that of a searchable
  99. directory, since the canonicalize_filename_mode_stk code won't
  100. check this later anyway when it checks an ordinary file name
  101. component within END. END must either be empty, or start with a
  102. slash. */
  103. static bool _GL_ATTRIBUTE_PURE
  104. suffix_requires_dir_check (char const *end)
  105. {
  106. /* If END does not start with a slash, the suffix is OK. */
  107. while (ISSLASH (*end))
  108. {
  109. /* Two or more slashes act like a single slash. */
  110. do
  111. end++;
  112. while (ISSLASH (*end));
  113. switch (*end++)
  114. {
  115. default: return false; /* An ordinary file name component is OK. */
  116. case '\0': return true; /* Trailing "/" is trouble. */
  117. case '.': break; /* Possibly "." or "..". */
  118. }
  119. /* Trailing "/.", or "/.." even if not trailing, is trouble. */
  120. if (!*end || (*end == '.' && (!end[1] || ISSLASH (end[1]))))
  121. return true;
  122. }
  123. return false;
  124. }
  125. /* Append this to a file name to test whether it is a searchable directory.
  126. On POSIX platforms "/" suffices, but "/./" is sometimes needed on
  127. macOS 10.13 <https://bugs.gnu.org/30350>, and should also work on
  128. platforms like AIX 7.2 that need at least "/.". */
  129. # if defined _LIBC || defined LSTAT_FOLLOWS_SLASHED_SYMLINK
  130. static char const dir_suffix[] = "/";
  131. # else
  132. static char const dir_suffix[] = "/./";
  133. # endif
  134. /* Return true if DIR is a searchable dir, false (setting errno) otherwise.
  135. DIREND points to the NUL byte at the end of the DIR string.
  136. Store garbage into DIREND[0 .. strlen (dir_suffix)]. */
  137. static bool
  138. dir_check (char *dir, char *dirend)
  139. {
  140. strcpy (dirend, dir_suffix);
  141. return file_accessible (dir);
  142. }
  143. static idx_t
  144. get_path_max (void)
  145. {
  146. # ifdef PATH_MAX
  147. long int path_max = PATH_MAX;
  148. # else
  149. /* The caller invoked realpath with a null RESOLVED, even though
  150. PATH_MAX is not defined as a constant. The glibc manual says
  151. programs should not do this, and POSIX says the behavior is undefined.
  152. Historically, glibc here used the result of pathconf, or 1024 if that
  153. failed; stay consistent with this (dubious) historical practice. */
  154. int err = errno;
  155. long int path_max = __pathconf ("/", _PC_PATH_MAX);
  156. __set_errno (err);
  157. # endif
  158. return path_max < 0 ? 1024 : path_max <= IDX_MAX ? path_max : IDX_MAX;
  159. }
  160. /* Act like __realpath (see below), with an additional argument
  161. rname_buf that can be used as temporary storage.
  162. If GCC_LINT is defined, do not inline this function with GCC 10.1
  163. and later, to avoid creating a pointer to the stack that GCC
  164. -Wreturn-local-addr incorrectly complains about. See:
  165. https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93644
  166. Although the noinline attribute can hurt performance a bit, no better way
  167. to pacify GCC is known; even an explicit #pragma does not pacify GCC.
  168. When the GCC bug is fixed this workaround should be limited to the
  169. broken GCC versions. */
  170. # if __GNUC_PREREQ (10, 1)
  171. # if defined GCC_LINT || defined lint
  172. __attribute__ ((__noinline__))
  173. # elif __OPTIMIZE__ && !__NO_INLINE__
  174. # define GCC_BOGUS_WRETURN_LOCAL_ADDR
  175. # endif
  176. # endif
  177. static char *
  178. realpath_stk (const char *name, char *resolved,
  179. struct scratch_buffer *rname_buf)
  180. {
  181. char *dest;
  182. char const *start;
  183. char const *end;
  184. int num_links = 0;
  185. if (name == NULL)
  186. {
  187. /* As per Single Unix Specification V2 we must return an error if
  188. either parameter is a null pointer. We extend this to allow
  189. the RESOLVED parameter to be NULL in case the we are expected to
  190. allocate the room for the return value. */
  191. __set_errno (EINVAL);
  192. return NULL;
  193. }
  194. if (name[0] == '\0')
  195. {
  196. /* As per Single Unix Specification V2 we must return an error if
  197. the name argument points to an empty string. */
  198. __set_errno (ENOENT);
  199. return NULL;
  200. }
  201. struct scratch_buffer extra_buffer, link_buffer;
  202. scratch_buffer_init (&extra_buffer);
  203. scratch_buffer_init (&link_buffer);
  204. scratch_buffer_init (rname_buf);
  205. char *rname_on_stack = rname_buf->data;
  206. char *rname = rname_on_stack;
  207. bool end_in_extra_buffer = false;
  208. bool failed = true;
  209. /* This is always zero for Posix hosts, but can be 2 for MS-Windows
  210. and MS-DOS X:/foo/bar file names. */
  211. idx_t prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
  212. if (!IS_ABSOLUTE_FILE_NAME (name))
  213. {
  214. while (!__getcwd (rname, rname_buf->length))
  215. {
  216. if (errno != ERANGE)
  217. {
  218. dest = rname;
  219. goto error;
  220. }
  221. if (!scratch_buffer_grow (rname_buf))
  222. goto error_nomem;
  223. rname = rname_buf->data;
  224. }
  225. dest = __rawmemchr (rname, '\0');
  226. start = name;
  227. prefix_len = FILE_SYSTEM_PREFIX_LEN (rname);
  228. }
  229. else
  230. {
  231. dest = __mempcpy (rname, name, prefix_len);
  232. *dest++ = '/';
  233. if (DOUBLE_SLASH_IS_DISTINCT_ROOT)
  234. {
  235. if (prefix_len == 0 /* implies ISSLASH (name[0]) */
  236. && ISSLASH (name[1]) && !ISSLASH (name[2]))
  237. *dest++ = '/';
  238. *dest = '\0';
  239. }
  240. start = name + prefix_len;
  241. }
  242. for ( ; *start; start = end)
  243. {
  244. /* Skip sequence of multiple file name separators. */
  245. while (ISSLASH (*start))
  246. ++start;
  247. /* Find end of component. */
  248. for (end = start; *end && !ISSLASH (*end); ++end)
  249. /* Nothing. */;
  250. /* Length of this file name component; it can be zero if a file
  251. name ends in '/'. */
  252. idx_t startlen = end - start;
  253. if (startlen == 0)
  254. break;
  255. else if (startlen == 1 && start[0] == '.')
  256. /* nothing */;
  257. else if (startlen == 2 && start[0] == '.' && start[1] == '.')
  258. {
  259. /* Back up to previous component, ignore if at root already. */
  260. if (dest > rname + prefix_len + 1)
  261. for (--dest; dest > rname && !ISSLASH (dest[-1]); --dest)
  262. continue;
  263. if (DOUBLE_SLASH_IS_DISTINCT_ROOT
  264. && dest == rname + 1 && !prefix_len
  265. && ISSLASH (*dest) && !ISSLASH (dest[1]))
  266. dest++;
  267. }
  268. else
  269. {
  270. if (!ISSLASH (dest[-1]))
  271. *dest++ = '/';
  272. while (rname + rname_buf->length - dest
  273. < startlen + sizeof dir_suffix)
  274. {
  275. idx_t dest_offset = dest - rname;
  276. if (!scratch_buffer_grow_preserve (rname_buf))
  277. goto error_nomem;
  278. rname = rname_buf->data;
  279. dest = rname + dest_offset;
  280. }
  281. dest = __mempcpy (dest, start, startlen);
  282. *dest = '\0';
  283. char *buf;
  284. ssize_t n;
  285. while (true)
  286. {
  287. buf = link_buffer.data;
  288. idx_t bufsize = link_buffer.length;
  289. n = __readlink (rname, buf, bufsize - 1);
  290. if (n < bufsize - 1)
  291. break;
  292. if (!scratch_buffer_grow (&link_buffer))
  293. goto error_nomem;
  294. }
  295. if (0 <= n)
  296. {
  297. if (++num_links > __eloop_threshold ())
  298. {
  299. __set_errno (ELOOP);
  300. goto error;
  301. }
  302. buf[n] = '\0';
  303. char *extra_buf = extra_buffer.data;
  304. idx_t end_idx IF_LINT (= 0);
  305. if (end_in_extra_buffer)
  306. end_idx = end - extra_buf;
  307. size_t len = strlen (end);
  308. if (INT_ADD_OVERFLOW (len, n))
  309. {
  310. __set_errno (ENOMEM);
  311. goto error_nomem;
  312. }
  313. while (extra_buffer.length <= len + n)
  314. {
  315. if (!scratch_buffer_grow_preserve (&extra_buffer))
  316. goto error_nomem;
  317. extra_buf = extra_buffer.data;
  318. }
  319. if (end_in_extra_buffer)
  320. end = extra_buf + end_idx;
  321. /* Careful here, end may be a pointer into extra_buf... */
  322. memmove (&extra_buf[n], end, len + 1);
  323. name = end = memcpy (extra_buf, buf, n);
  324. end_in_extra_buffer = true;
  325. if (IS_ABSOLUTE_FILE_NAME (buf))
  326. {
  327. idx_t pfxlen = FILE_SYSTEM_PREFIX_LEN (buf);
  328. dest = __mempcpy (rname, buf, pfxlen);
  329. *dest++ = '/'; /* It's an absolute symlink */
  330. if (DOUBLE_SLASH_IS_DISTINCT_ROOT)
  331. {
  332. if (ISSLASH (buf[1]) && !ISSLASH (buf[2]) && !pfxlen)
  333. *dest++ = '/';
  334. *dest = '\0';
  335. }
  336. /* Install the new prefix to be in effect hereafter. */
  337. prefix_len = pfxlen;
  338. }
  339. else
  340. {
  341. /* Back up to previous component, ignore if at root
  342. already: */
  343. if (dest > rname + prefix_len + 1)
  344. for (--dest; dest > rname && !ISSLASH (dest[-1]); --dest)
  345. continue;
  346. if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
  347. && ISSLASH (*dest) && !ISSLASH (dest[1]) && !prefix_len)
  348. dest++;
  349. }
  350. }
  351. else if (! (suffix_requires_dir_check (end)
  352. ? dir_check (rname, dest)
  353. : errno == EINVAL))
  354. goto error;
  355. }
  356. }
  357. if (dest > rname + prefix_len + 1 && ISSLASH (dest[-1]))
  358. --dest;
  359. if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1 && !prefix_len
  360. && ISSLASH (*dest) && !ISSLASH (dest[1]))
  361. dest++;
  362. failed = false;
  363. error:
  364. *dest++ = '\0';
  365. if (resolved != NULL && dest - rname <= get_path_max ())
  366. rname = strcpy (resolved, rname);
  367. error_nomem:
  368. scratch_buffer_free (&extra_buffer);
  369. scratch_buffer_free (&link_buffer);
  370. if (failed || rname == resolved)
  371. {
  372. scratch_buffer_free (rname_buf);
  373. return failed ? NULL : resolved;
  374. }
  375. return scratch_buffer_dupfree (rname_buf, dest - rname);
  376. }
  377. /* Return the canonical absolute name of file NAME. A canonical name
  378. does not contain any ".", ".." components nor any repeated file name
  379. separators ('/') or symlinks. All file name components must exist. If
  380. RESOLVED is null, the result is malloc'd; otherwise, if the
  381. canonical name is PATH_MAX chars or more, returns null with 'errno'
  382. set to ENAMETOOLONG; if the name fits in fewer than PATH_MAX chars,
  383. returns the name in RESOLVED. If the name cannot be resolved and
  384. RESOLVED is non-NULL, it contains the name of the first component
  385. that cannot be resolved. If the name can be resolved, RESOLVED
  386. holds the same value as the value returned. */
  387. char *
  388. __realpath (const char *name, char *resolved)
  389. {
  390. #ifdef GCC_BOGUS_WRETURN_LOCAL_ADDR
  391. #warning "GCC might issue a bogus -Wreturn-local-addr warning here."
  392. #warning "See <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93644>."
  393. #endif
  394. struct scratch_buffer rname_buffer;
  395. return realpath_stk (name, resolved, &rname_buffer);
  396. }
  397. libc_hidden_def (__realpath)
  398. versioned_symbol (libc, __realpath, realpath, GLIBC_2_3);
  399. #endif /* defined _LIBC || !FUNC_REALPATH_WORKS */
  400. #if SHLIB_COMPAT(libc, GLIBC_2_0, GLIBC_2_3)
  401. char *
  402. attribute_compat_text_section
  403. __old_realpath (const char *name, char *resolved)
  404. {
  405. if (resolved == NULL)
  406. {
  407. __set_errno (EINVAL);
  408. return NULL;
  409. }
  410. return __realpath (name, resolved);
  411. }
  412. compat_symbol (libc, __old_realpath, realpath, GLIBC_2_0);
  413. #endif
  414. char *
  415. __canonicalize_file_name (const char *name)
  416. {
  417. return __realpath (name, NULL);
  418. }
  419. weak_alias (__canonicalize_file_name, canonicalize_file_name)