1 /* vi: set sw=4 ts=4: */
3 * xreadlink.c - safe implementation of readlink.
4 * Returns a NULL on failure...
10 * NOTE: This function returns a malloced char* that you will have to free
13 char *xmalloc_readlink(const char *path)
15 enum { GROWBY = 80 }; /* how large we will grow strings by */
18 int bufsize = 0, readsize = 0;
22 buf = xrealloc(buf, bufsize);
23 readsize = readlink(path, buf, bufsize);
28 } while (bufsize < readsize + 1);
36 * This routine is not the same as realpath(), which
37 * canonicalizes the given path completely. This routine only
38 * follows trailing symlinks until a real file is reached and
39 * returns its name. If the path ends in a dangling link or if
40 * the target doesn't exist, the path is returned in any case.
41 * Intermediate symlinks in the path are not expanded -- only
43 * A malloced char* is returned, which must be freed by the caller.
45 char *xmalloc_follow_symlinks(const char *path)
51 int looping = MAXSYMLINKS + 1;
58 linkpath = xmalloc_readlink(buf);
60 /* not a symlink, or doesn't exist */
61 if (errno == EINVAL || errno == ENOENT)
63 goto free_buf_ret_null;
73 if (*linkpath != '/') {
74 bufsize += strlen(linkpath);
75 buf = xrealloc(buf, bufsize);
76 lpc = bb_get_last_path_component_strip(buf);
77 strcpy(lpc, linkpath);
83 bufsize = strlen(buf) + 1;
88 char *xmalloc_readlink_or_warn(const char *path)
90 char *buf = xmalloc_readlink(path);
92 /* EINVAL => "file: Invalid argument" => puzzled user */
93 bb_error_msg("%s: cannot read link (not a symlink?)", path);
100 char *xmalloc_realpath(const char *path)
102 #if defined(__GLIBC__) && !defined(__UCLIBC__)
103 /* glibc provides a non-standard extension */
104 return realpath(path, NULL);
106 char buf[PATH_MAX+1];
108 /* on error returns NULL (xstrdup(NULL) ==NULL) */
109 return xstrdup(realpath(path, buf));