unistr/u{8,16,32}-uctomb: Avoid possible trouble with huge strings.
[gnulib.git] / lib / readlinkat.c
blob68ec65ebfc58c4d8f078a1e1f0503be24b717462
1 /* Read a symlink relative to an open directory.
2 Copyright (C) 2009-2020 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 /* written by Eric Blake */
19 #include <config.h>
21 /* Specification. */
22 #include <unistd.h>
24 #include <errno.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/stat.h>
29 #if HAVE_READLINKAT
31 # undef readlinkat
33 ssize_t
34 rpl_readlinkat (int fd, char const *file, char *buf, size_t len)
36 # if READLINK_TRAILING_SLASH_BUG
37 size_t file_len = strlen (file);
38 if (file_len && file[file_len - 1] == '/')
40 /* Even if FILE without the slash is a symlink to a directory,
41 both lstat() and stat() must resolve the trailing slash to
42 the directory rather than the symlink. We can therefore
43 safely use stat() to distinguish between EINVAL and
44 ENOTDIR/ENOENT, avoiding extra overhead of rpl_lstat(). */
45 struct stat st;
46 if (stat (file, &st) == 0)
47 errno = EINVAL;
48 return -1;
50 # endif /* READLINK_TRAILING_SLASH_BUG */
51 return readlinkat (fd, file, buf, len);
54 #else
56 /* Gnulib provides a readlink stub for mingw; use it for distinction
57 between EINVAL and ENOENT, rather than always failing with ENOSYS. */
59 /* POSIX 2008 says that unlike readlink, readlinkat returns 0 for
60 success instead of the buffer length. But this would render
61 readlinkat worthless since readlink does not guarantee a
62 NUL-terminated buffer. Assume this was a bug in POSIX. */
64 /* Read the contents of symlink FILE into buffer BUF of size LEN, in the
65 directory open on descriptor FD. If possible, do it without changing
66 the working directory. Otherwise, resort to using save_cwd/fchdir,
67 then readlink/restore_cwd. If either the save_cwd or the restore_cwd
68 fails, then give a diagnostic and exit nonzero. */
70 # define AT_FUNC_NAME readlinkat
71 # define AT_FUNC_F1 readlink
72 # define AT_FUNC_POST_FILE_PARAM_DECLS , char *buf, size_t len
73 # define AT_FUNC_POST_FILE_ARGS , buf, len
74 # define AT_FUNC_RESULT ssize_t
75 # include "at-func.c"
76 # undef AT_FUNC_NAME
77 # undef AT_FUNC_F1
78 # undef AT_FUNC_POST_FILE_PARAM_DECLS
79 # undef AT_FUNC_POST_FILE_ARGS
80 # undef AT_FUNC_RESULT
82 #endif