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.
11 /* Some systems (eg Hurd) do not have MAXSYMLINKS definition,
12 * set it to some reasonable value if it isn't defined */
14 # define MAXSYMLINKS 20
18 * NOTE: This function returns a malloced char* that you will have to free
21 char* FAST_FUNC xmalloc_readlink(const char *path)
23 enum { GROWBY = 80 }; /* how large we will grow strings by */
26 int bufsize = 0, readsize = 0;
30 buf = xrealloc(buf, bufsize);
31 readsize = readlink(path, buf, bufsize);
36 } while (bufsize < readsize + 1);
44 * This routine is not the same as realpath(), which
45 * canonicalizes the given path completely. This routine only
46 * follows trailing symlinks until a real file is reached and
47 * returns its name. If the path ends in a dangling link or if
48 * the target doesn't exist, the path is returned in any case.
49 * Intermediate symlinks in the path are not expanded -- only
51 * A malloced char* is returned, which must be freed by the caller.
53 char* FAST_FUNC xmalloc_follow_symlinks(const char *path)
59 int looping = MAXSYMLINKS + 1;
65 linkpath = xmalloc_readlink(buf);
67 /* not a symlink, or doesn't exist */
68 if (errno == EINVAL || errno == ENOENT)
70 goto free_buf_ret_null;
80 if (*linkpath != '/') {
81 bufsize += strlen(linkpath);
82 buf = xrealloc(buf, bufsize);
83 lpc = bb_get_last_path_component_strip(buf);
84 strcpy(lpc, linkpath);
90 bufsize = strlen(buf) + 1;
95 char* FAST_FUNC xmalloc_readlink_or_warn(const char *path)
97 char *buf = xmalloc_readlink(path);
99 /* EINVAL => "file: Invalid argument" => puzzled user */
100 const char *errmsg = "not a symlink";
103 errmsg = strerror(err);
104 bb_error_msg("%s: cannot read link: %s", path, errmsg);
109 char* FAST_FUNC xmalloc_realpath(const char *path)
111 /* NB: uclibc also defines __GLIBC__
112 * Therefore the test "if glibc, or uclibc >= 0.9.31" looks a bit weird:
114 #if defined(__GLIBC__) && \
115 (!defined(__UCLIBC__) || UCLIBC_VERSION >= KERNEL_VERSION(0, 9, 31))
116 /* glibc provides a non-standard extension */
117 /* new: POSIX.1-2008 specifies this behavior as well */
118 return realpath(path, NULL);
120 char buf[PATH_MAX+1];
122 /* on error returns NULL (xstrdup(NULL) == NULL) */
123 return xstrdup(realpath(path, buf));