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;
57 linkpath = xmalloc_readlink(buf);
59 /* not a symlink, or doesn't exist */
60 if (errno == EINVAL || errno == ENOENT)
62 goto free_buf_ret_null;
72 if (*linkpath != '/') {
73 bufsize += strlen(linkpath);
74 buf = xrealloc(buf, bufsize);
75 lpc = bb_get_last_path_component_strip(buf);
76 strcpy(lpc, linkpath);
82 bufsize = strlen(buf) + 1;
87 char *xmalloc_readlink_or_warn(const char *path)
89 char *buf = xmalloc_readlink(path);
91 /* EINVAL => "file: Invalid argument" => puzzled user */
92 bb_error_msg("%s: cannot read link (not a symlink?)", path);
99 char *xmalloc_realpath(const char *path)
101 #if defined(__GLIBC__) && !defined(__UCLIBC__)
102 /* glibc provides a non-standard extension */
103 return realpath(path, NULL);
105 char buf[PATH_MAX+1];
107 /* on error returns NULL (xstrdup(NULL) ==NULL) */
108 return xstrdup(realpath(path, buf));