canonicalize-lgpl.c 15 KB

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