blob: 4d87b944d6d8489351c6462aa7236847d0408451 [file] [log] [blame]
"Robert P. J. Day"63fc1a92006-07-02 19:47:05 +00001/* vi: set sw=4 ts=4: */
Mark Whitley8a633262001-04-30 18:17:00 +00002/*
Eric Andersen28355a32001-05-07 17:48:28 +00003 * xreadlink.c - safe implementation of readlink.
4 * Returns a NULL on failure...
Mark Whitley8a633262001-04-30 18:17:00 +00005 */
6
Denis Vlasenkoa9b60e92007-01-04 17:59:59 +00007#include "libbb.h"
Mark Whitley8a633262001-04-30 18:17:00 +00008
9/*
10 * NOTE: This function returns a malloced char* that you will have to free
11 * yourself. You have been warned.
12 */
Denis Vlasenkobeffd432007-09-05 11:30:34 +000013char *xmalloc_readlink(const char *path)
Tim Rikerc1ef7bd2006-01-25 00:08:53 +000014{
Rob Landleybc68cd12006-03-10 19:22:06 +000015 enum { GROWBY = 80 }; /* how large we will grow strings by */
Mark Whitley8a633262001-04-30 18:17:00 +000016
Eric Andersenc7bda1c2004-03-15 08:29:22 +000017 char *buf = NULL;
Mark Whitley8a633262001-04-30 18:17:00 +000018 int bufsize = 0, readsize = 0;
19
20 do {
21 buf = xrealloc(buf, bufsize += GROWBY);
Denis Vlasenkobeffd432007-09-05 11:30:34 +000022 readsize = readlink(path, buf, bufsize);
Eric Andersen28355a32001-05-07 17:48:28 +000023 if (readsize == -1) {
Glenn L McGrath18bbd9b2004-08-11 03:50:30 +000024 free(buf);
25 return NULL;
Eric Andersen28355a32001-05-07 17:48:28 +000026 }
Denis Vlasenkobeffd432007-09-05 11:30:34 +000027 } while (bufsize < readsize + 1);
Mark Whitley8a633262001-04-30 18:17:00 +000028
29 buf[readsize] = '\0';
30
31 return buf;
Eric Andersenc7bda1c2004-03-15 08:29:22 +000032}
Denis Vlasenkoa9b60e92007-01-04 17:59:59 +000033
Denis Vlasenkobeffd432007-09-05 11:30:34 +000034char *xmalloc_readlink_or_warn(const char *path)
35{
36 char *buf = xmalloc_readlink(path);
37 if (!buf) {
38 /* EINVAL => "file: Invalid argument" => puzzled user */
39 bb_error_msg("%s: cannot read link (not a symlink?)", path);
40 }
41 return buf;
42}
43
44/* UNUSED */
45#if 0
Denis Vlasenkoa9b60e92007-01-04 17:59:59 +000046char *xmalloc_realpath(const char *path)
47{
Denis Vlasenko218f2f42007-01-24 22:02:01 +000048#if defined(__GLIBC__) && !defined(__UCLIBC__)
Denis Vlasenkoa9b60e92007-01-04 17:59:59 +000049 /* glibc provides a non-standard extension */
50 return realpath(path, NULL);
51#else
52 char buf[PATH_MAX+1];
53
54 /* on error returns NULL (xstrdup(NULL) ==NULL) */
55 return xstrdup(realpath(path, buf));
56#endif
57}
Denis Vlasenkobeffd432007-09-05 11:30:34 +000058#endif