blob: c7227d1ddf12ee91915178dc6adc843d51940eb1 [file] [log] [blame]
Mark Whitley8a633262001-04-30 18:17:00 +00001/*
Eric Andersen28355a32001-05-07 17:48:28 +00002 * xreadlink.c - safe implementation of readlink.
3 * Returns a NULL on failure...
Mark Whitley8a633262001-04-30 18:17:00 +00004 */
5
6#include <stdio.h>
7
8/*
9 * NOTE: This function returns a malloced char* that you will have to free
10 * yourself. You have been warned.
11 */
12
13#include <unistd.h>
14#include "libbb.h"
15
Rob Landleydfba7412006-03-06 20:47:33 +000016char *xreadlink(const char *path)
Tim Rikerc1ef7bd2006-01-25 00:08:53 +000017{
Rob Landleybc68cd12006-03-10 19:22:06 +000018 enum { GROWBY = 80 }; /* how large we will grow strings by */
Mark Whitley8a633262001-04-30 18:17:00 +000019
Eric Andersenc7bda1c2004-03-15 08:29:22 +000020 char *buf = NULL;
Mark Whitley8a633262001-04-30 18:17:00 +000021 int bufsize = 0, readsize = 0;
22
23 do {
24 buf = xrealloc(buf, bufsize += GROWBY);
25 readsize = readlink(path, buf, bufsize); /* 1st try */
Eric Andersen28355a32001-05-07 17:48:28 +000026 if (readsize == -1) {
Glenn L McGrath18bbd9b2004-08-11 03:50:30 +000027 bb_perror_msg("%s", path);
28 free(buf);
29 return NULL;
Eric Andersen28355a32001-05-07 17:48:28 +000030 }
Eric Andersenc7bda1c2004-03-15 08:29:22 +000031 }
Mark Whitley8a633262001-04-30 18:17:00 +000032 while (bufsize < readsize + 1);
33
34 buf[readsize] = '\0';
35
36 return buf;
Eric Andersenc7bda1c2004-03-15 08:29:22 +000037}