Mark Whitley | 8a63326 | 2001-04-30 18:17:00 +0000 | [diff] [blame] | 1 | /* |
Eric Andersen | 28355a3 | 2001-05-07 17:48:28 +0000 | [diff] [blame] | 2 | * xreadlink.c - safe implementation of readlink. |
| 3 | * Returns a NULL on failure... |
Mark Whitley | 8a63326 | 2001-04-30 18:17:00 +0000 | [diff] [blame] | 4 | */ |
| 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 Landley | dfba741 | 2006-03-06 20:47:33 +0000 | [diff] [blame] | 16 | char *xreadlink(const char *path) |
Tim Riker | c1ef7bd | 2006-01-25 00:08:53 +0000 | [diff] [blame] | 17 | { |
Rob Landley | bc68cd1 | 2006-03-10 19:22:06 +0000 | [diff] [blame] | 18 | enum { GROWBY = 80 }; /* how large we will grow strings by */ |
Mark Whitley | 8a63326 | 2001-04-30 18:17:00 +0000 | [diff] [blame] | 19 | |
Eric Andersen | c7bda1c | 2004-03-15 08:29:22 +0000 | [diff] [blame] | 20 | char *buf = NULL; |
Mark Whitley | 8a63326 | 2001-04-30 18:17:00 +0000 | [diff] [blame] | 21 | int bufsize = 0, readsize = 0; |
| 22 | |
| 23 | do { |
| 24 | buf = xrealloc(buf, bufsize += GROWBY); |
| 25 | readsize = readlink(path, buf, bufsize); /* 1st try */ |
Eric Andersen | 28355a3 | 2001-05-07 17:48:28 +0000 | [diff] [blame] | 26 | if (readsize == -1) { |
Glenn L McGrath | 18bbd9b | 2004-08-11 03:50:30 +0000 | [diff] [blame] | 27 | bb_perror_msg("%s", path); |
| 28 | free(buf); |
| 29 | return NULL; |
Eric Andersen | 28355a3 | 2001-05-07 17:48:28 +0000 | [diff] [blame] | 30 | } |
Eric Andersen | c7bda1c | 2004-03-15 08:29:22 +0000 | [diff] [blame] | 31 | } |
Mark Whitley | 8a63326 | 2001-04-30 18:17:00 +0000 | [diff] [blame] | 32 | while (bufsize < readsize + 1); |
| 33 | |
| 34 | buf[readsize] = '\0'; |
| 35 | |
| 36 | return buf; |
Eric Andersen | c7bda1c | 2004-03-15 08:29:22 +0000 | [diff] [blame] | 37 | } |