blob: 18a8b9467bdde152f7a9f55da324aeb42dfaace0 [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 */
13
Denis Vlasenko6ca04442007-02-11 16:19:28 +000014char *xmalloc_readlink_or_warn(const char *path)
Tim Rikerc1ef7bd2006-01-25 00:08:53 +000015{
Rob Landleybc68cd12006-03-10 19:22:06 +000016 enum { GROWBY = 80 }; /* how large we will grow strings by */
Mark Whitley8a633262001-04-30 18:17:00 +000017
Eric Andersenc7bda1c2004-03-15 08:29:22 +000018 char *buf = NULL;
Mark Whitley8a633262001-04-30 18:17:00 +000019 int bufsize = 0, readsize = 0;
20
21 do {
22 buf = xrealloc(buf, bufsize += GROWBY);
23 readsize = readlink(path, buf, bufsize); /* 1st try */
Eric Andersen28355a32001-05-07 17:48:28 +000024 if (readsize == -1) {
Glenn L McGrath18bbd9b2004-08-11 03:50:30 +000025 bb_perror_msg("%s", path);
26 free(buf);
27 return NULL;
Eric Andersen28355a32001-05-07 17:48:28 +000028 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +000029 }
Mark Whitley8a633262001-04-30 18:17:00 +000030 while (bufsize < readsize + 1);
31
32 buf[readsize] = '\0';
33
34 return buf;
Eric Andersenc7bda1c2004-03-15 08:29:22 +000035}
Denis Vlasenkoa9b60e92007-01-04 17:59:59 +000036
37char *xmalloc_realpath(const char *path)
38{
Denis Vlasenko218f2f42007-01-24 22:02:01 +000039#if defined(__GLIBC__) && !defined(__UCLIBC__)
Denis Vlasenkoa9b60e92007-01-04 17:59:59 +000040 /* glibc provides a non-standard extension */
41 return realpath(path, NULL);
42#else
43 char buf[PATH_MAX+1];
44
45 /* on error returns NULL (xstrdup(NULL) ==NULL) */
46 return xstrdup(realpath(path, buf));
47#endif
48}