canonicalize-lgpl.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /* Return the canonical absolute name of a given file.
  2. Copyright (C) 1996-2023 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 <string.h>
  27. #include <sys/stat.h>
  28. #include <unistd.h>
  29. #include <eloop-threshold.h>
  30. #include <filename.h>
  31. #include <idx.h>
  32. #include <intprops.h>
  33. #include <scratch_buffer.h>
  34. #ifdef _LIBC
  35. # include <shlib-compat.h>
  36. # define GCC_LINT 1
  37. # define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
  38. #else
  39. # define __canonicalize_file_name canonicalize_file_name
  40. # define __realpath realpath
  41. # define __strdup strdup
  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. /* Scratch buffers used by realpath_stk and managed by __realpath. */
  161. struct realpath_bufs
  162. {
  163. struct scratch_buffer rname;
  164. struct scratch_buffer extra;
  165. struct scratch_buffer link;
  166. };
  167. static char *
  168. realpath_stk (const char *name, char *resolved, struct realpath_bufs *bufs)
  169. {
  170. char *dest;
  171. char const *start;
  172. char const *end;
  173. int num_links = 0;
  174. if (name == NULL)
  175. {
  176. /* As per Single Unix Specification V2 we must return an error if
  177. either parameter is a null pointer. We extend this to allow
  178. the RESOLVED parameter to be NULL in case the we are expected to
  179. allocate the room for the return value. */
  180. __set_errno (EINVAL);
  181. return NULL;
  182. }
  183. if (name[0] == '\0')
  184. {
  185. /* As per Single Unix Specification V2 we must return an error if
  186. the name argument points to an empty string. */
  187. __set_errno (ENOENT);
  188. return NULL;
  189. }
  190. char *rname = bufs->rname.data;
  191. bool end_in_extra_buffer = false;
  192. bool failed = true;
  193. /* This is always zero for Posix hosts, but can be 2 for MS-Windows
  194. and MS-DOS X:/foo/bar file names. */
  195. idx_t prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
  196. if (!IS_ABSOLUTE_FILE_NAME (name))
  197. {
  198. while (!__getcwd (bufs->rname.data, bufs->rname.length))
  199. {
  200. if (errno != ERANGE)
  201. {
  202. dest = rname;
  203. goto error;
  204. }
  205. if (!scratch_buffer_grow (&bufs->rname))
  206. return NULL;
  207. rname = bufs->rname.data;
  208. }
  209. dest = __rawmemchr (rname, '\0');
  210. start = name;
  211. prefix_len = FILE_SYSTEM_PREFIX_LEN (rname);
  212. }
  213. else
  214. {
  215. dest = __mempcpy (rname, name, prefix_len);
  216. *dest++ = '/';
  217. if (DOUBLE_SLASH_IS_DISTINCT_ROOT)
  218. {
  219. if (prefix_len == 0 /* implies ISSLASH (name[0]) */
  220. && ISSLASH (name[1]) && !ISSLASH (name[2]))
  221. *dest++ = '/';
  222. *dest = '\0';
  223. }
  224. start = name + prefix_len;
  225. }
  226. for ( ; *start; start = end)
  227. {
  228. /* Skip sequence of multiple file name separators. */
  229. while (ISSLASH (*start))
  230. ++start;
  231. /* Find end of component. */
  232. for (end = start; *end && !ISSLASH (*end); ++end)
  233. /* Nothing. */;
  234. /* Length of this file name component; it can be zero if a file
  235. name ends in '/'. */
  236. idx_t startlen = end - start;
  237. if (startlen == 0)
  238. break;
  239. else if (startlen == 1 && start[0] == '.')
  240. /* nothing */;
  241. else if (startlen == 2 && start[0] == '.' && start[1] == '.')
  242. {
  243. /* Back up to previous component, ignore if at root already. */
  244. if (dest > rname + prefix_len + 1)
  245. for (--dest; dest > rname && !ISSLASH (dest[-1]); --dest)
  246. continue;
  247. if (DOUBLE_SLASH_IS_DISTINCT_ROOT
  248. && dest == rname + 1 && !prefix_len
  249. && ISSLASH (*dest) && !ISSLASH (dest[1]))
  250. dest++;
  251. }
  252. else
  253. {
  254. if (!ISSLASH (dest[-1]))
  255. *dest++ = '/';
  256. while (rname + bufs->rname.length - dest
  257. < startlen + sizeof dir_suffix)
  258. {
  259. idx_t dest_offset = dest - rname;
  260. if (!scratch_buffer_grow_preserve (&bufs->rname))
  261. return NULL;
  262. rname = bufs->rname.data;
  263. dest = rname + dest_offset;
  264. }
  265. dest = __mempcpy (dest, start, startlen);
  266. *dest = '\0';
  267. char *buf;
  268. ssize_t n;
  269. while (true)
  270. {
  271. buf = bufs->link.data;
  272. idx_t bufsize = bufs->link.length;
  273. n = __readlink (rname, buf, bufsize - 1);
  274. if (n < bufsize - 1)
  275. break;
  276. if (!scratch_buffer_grow (&bufs->link))
  277. return NULL;
  278. }
  279. if (0 <= n)
  280. {
  281. if (++num_links > __eloop_threshold ())
  282. {
  283. __set_errno (ELOOP);
  284. goto error;
  285. }
  286. buf[n] = '\0';
  287. char *extra_buf = bufs->extra.data;
  288. idx_t end_idx IF_LINT (= 0);
  289. if (end_in_extra_buffer)
  290. end_idx = end - extra_buf;
  291. size_t len = strlen (end);
  292. if (INT_ADD_OVERFLOW (len, n))
  293. {
  294. __set_errno (ENOMEM);
  295. return NULL;
  296. }
  297. while (bufs->extra.length <= len + n)
  298. {
  299. if (!scratch_buffer_grow_preserve (&bufs->extra))
  300. return NULL;
  301. extra_buf = bufs->extra.data;
  302. }
  303. if (end_in_extra_buffer)
  304. end = extra_buf + end_idx;
  305. /* Careful here, end may be a pointer into extra_buf... */
  306. memmove (&extra_buf[n], end, len + 1);
  307. name = end = memcpy (extra_buf, buf, n);
  308. end_in_extra_buffer = true;
  309. if (IS_ABSOLUTE_FILE_NAME (buf))
  310. {
  311. idx_t pfxlen = FILE_SYSTEM_PREFIX_LEN (buf);
  312. dest = __mempcpy (rname, buf, pfxlen);
  313. *dest++ = '/'; /* It's an absolute symlink */
  314. if (DOUBLE_SLASH_IS_DISTINCT_ROOT)
  315. {
  316. if (ISSLASH (buf[1]) && !ISSLASH (buf[2]) && !pfxlen)
  317. *dest++ = '/';
  318. *dest = '\0';
  319. }
  320. /* Install the new prefix to be in effect hereafter. */
  321. prefix_len = pfxlen;
  322. }
  323. else
  324. {
  325. /* Back up to previous component, ignore if at root
  326. already: */
  327. if (dest > rname + prefix_len + 1)
  328. for (--dest; dest > rname && !ISSLASH (dest[-1]); --dest)
  329. continue;
  330. if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
  331. && ISSLASH (*dest) && !ISSLASH (dest[1]) && !prefix_len)
  332. dest++;
  333. }
  334. }
  335. else if (! (suffix_requires_dir_check (end)
  336. ? dir_check (rname, dest)
  337. : errno == EINVAL))
  338. goto error;
  339. }
  340. }
  341. if (dest > rname + prefix_len + 1 && ISSLASH (dest[-1]))
  342. --dest;
  343. if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1 && !prefix_len
  344. && ISSLASH (*dest) && !ISSLASH (dest[1]))
  345. dest++;
  346. failed = false;
  347. error:
  348. *dest++ = '\0';
  349. if (resolved != NULL)
  350. {
  351. /* Copy the full result on success or partial result if failure was due
  352. to the path not existing or not being accessible. */
  353. if ((!failed || errno == ENOENT || errno == EACCES)
  354. && dest - rname <= get_path_max ())
  355. {
  356. strcpy (resolved, rname);
  357. if (failed)
  358. return NULL;
  359. else
  360. return resolved;
  361. }
  362. if (!failed)
  363. __set_errno (ENAMETOOLONG);
  364. return NULL;
  365. }
  366. else
  367. {
  368. if (failed)
  369. return NULL;
  370. else
  371. return __strdup (bufs->rname.data);
  372. }
  373. }
  374. /* Return the canonical absolute name of file NAME. A canonical name
  375. does not contain any ".", ".." components nor any repeated file name
  376. separators ('/') or symlinks. All file name components must exist. If
  377. RESOLVED is null, the result is malloc'd; otherwise, if the
  378. canonical name is PATH_MAX chars or more, returns null with 'errno'
  379. set to ENAMETOOLONG; if the name fits in fewer than PATH_MAX chars,
  380. returns the name in RESOLVED. If the name cannot be resolved and
  381. RESOLVED is non-NULL, it contains the name of the first component
  382. that cannot be resolved. If the name can be resolved, RESOLVED
  383. holds the same value as the value returned. */
  384. char *
  385. __realpath (const char *name, char *resolved)
  386. {
  387. struct realpath_bufs bufs;
  388. scratch_buffer_init (&bufs.rname);
  389. scratch_buffer_init (&bufs.extra);
  390. scratch_buffer_init (&bufs.link);
  391. char *result = realpath_stk (name, resolved, &bufs);
  392. scratch_buffer_free (&bufs.link);
  393. scratch_buffer_free (&bufs.extra);
  394. scratch_buffer_free (&bufs.rname);
  395. return result;
  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)