blob: 14863d9d5f75cae98fdcdcba8235614677eced43 [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
7#include <stdio.h>
8
9/*
10 * NOTE: This function returns a malloced char* that you will have to free
11 * yourself. You have been warned.
12 */
13
14#include <unistd.h>
15#include "libbb.h"
16
Rob Landleydfba7412006-03-06 20:47:33 +000017char *xreadlink(const char *path)
Tim Rikerc1ef7bd2006-01-25 00:08:53 +000018{
Rob Landleybc68cd12006-03-10 19:22:06 +000019 enum { GROWBY = 80 }; /* how large we will grow strings by */
Mark Whitley8a633262001-04-30 18:17:00 +000020
Eric Andersenc7bda1c2004-03-15 08:29:22 +000021 char *buf = NULL;
Mark Whitley8a633262001-04-30 18:17:00 +000022 int bufsize = 0, readsize = 0;
23
24 do {
25 buf = xrealloc(buf, bufsize += GROWBY);
26 readsize = readlink(path, buf, bufsize); /* 1st try */
Eric Andersen28355a32001-05-07 17:48:28 +000027 if (readsize == -1) {
Glenn L McGrath18bbd9b2004-08-11 03:50:30 +000028 bb_perror_msg("%s", path);
29 free(buf);
30 return NULL;
Eric Andersen28355a32001-05-07 17:48:28 +000031 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +000032 }
Mark Whitley8a633262001-04-30 18:17:00 +000033 while (bufsize < readsize + 1);
34
35 buf[readsize] = '\0';
36
37 return buf;
Eric Andersenc7bda1c2004-03-15 08:29:22 +000038}