1 /* vi: set sw=4 ts=4: */
3 * xreadlink.c - safe implementation of readlink.
4 * Returns a NULL on failure.
6 * Licensed under GPLv2, see file LICENSE in this source tree.
10 /* Some systems (eg Hurd) do not have MAXSYMLINKS definition,
11 * set it to some reasonable value if it isn't defined */
13 # define MAXSYMLINKS 20
17 * NOTE: This function returns a malloced char* that you will have to free
20 char* FAST_FUNC xmalloc_readlink(const char *path)
22 enum { GROWBY = 80 }; /* how large we will grow strings by */
25 int bufsize = 0, readsize = 0;
29 buf = xrealloc(buf, bufsize);
30 readsize = readlink(path, buf, bufsize);
35 } while (bufsize < readsize + 1);
43 * This routine is not the same as realpath(), which
44 * canonicalizes the given path completely. This routine only
45 * follows trailing symlinks until a real file is reached and
46 * returns its name. If the path ends in a dangling link or if
47 * the target doesn't exist, the path is returned in any case.
48 * Intermediate symlinks in the path are not expanded -- only
50 * A malloced char* is returned, which must be freed by the caller.
52 char* FAST_FUNC xmalloc_follow_symlinks(const char *path)
58 int looping = MAXSYMLINKS + 1;
64 linkpath = xmalloc_readlink(buf);
66 /* not a symlink, or doesn't exist */
67 if (errno == EINVAL || errno == ENOENT)
69 goto free_buf_ret_null;
79 if (*linkpath != '/') {
80 bufsize += strlen(linkpath);
81 buf = xrealloc(buf, bufsize);
82 lpc = bb_get_last_path_component_strip(buf);
83 strcpy(lpc, linkpath);
89 bufsize = strlen(buf) + 1;
94 char* FAST_FUNC xmalloc_readlink_or_warn(const char *path)
96 char *buf = xmalloc_readlink(path);
98 /* EINVAL => "file: Invalid argument" => puzzled user */
99 const char *errmsg = "not a symlink";
102 errmsg = strerror(err);
103 bb_error_msg("%s: cannot read link: %s", path, errmsg);
108 char* FAST_FUNC xmalloc_realpath(const char *path)
110 /* NB: uclibc also defines __GLIBC__
111 * Therefore the test "if glibc, or uclibc >= 0.9.31" looks a bit weird:
113 #if defined(__GLIBC__) && \
114 (!defined(__UCLIBC__) || UCLIBC_VERSION >= KERNEL_VERSION(0, 9, 31))
115 /* glibc provides a non-standard extension */
116 /* new: POSIX.1-2008 specifies this behavior as well */
117 return realpath(path, NULL);
119 char buf[PATH_MAX+1];
121 /* on error returns NULL (xstrdup(NULL) == NULL) */
122 return xstrdup(realpath(path, buf));