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
11 * yourself. You have been warned.
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 canonicalizes
37 * the given path completely. this routine only follows trailing
38 * symlinks until a real file is reached, and returns its name.
39 * intermediate symlinks are not expanded. as above, a malloced
40 * char* is returned, which must be freed.
42 char *xmalloc_readlink_follow(const char *path)
48 int looping = MAXSYMLINKS + 1;
50 linkpath = xstrdup(path);
59 linkpath = xmalloc_readlink(buf);
61 if (errno == EINVAL) /* not a symlink */
66 if (linkpath[0] != '/') {
67 bufsize += strlen(linkpath);
68 buf = xrealloc(buf, bufsize);
69 lpc = bb_get_last_path_component_strip(buf);
70 strcpy(lpc, linkpath);
76 bufsize = strlen(buf) + 1;
81 char *xmalloc_readlink_or_warn(const char *path)
83 char *buf = xmalloc_readlink(path);
85 /* EINVAL => "file: Invalid argument" => puzzled user */
86 bb_error_msg("%s: cannot read link (not a symlink?)", path);
93 char *xmalloc_realpath(const char *path)
95 #if defined(__GLIBC__) && !defined(__UCLIBC__)
96 /* glibc provides a non-standard extension */
97 return realpath(path, NULL);
101 /* on error returns NULL (xstrdup(NULL) ==NULL) */
102 return xstrdup(realpath(path, buf));